John1984 John1984 - 7 months ago 22
Javascript Question

Insert a span around nth-word within a div

I'm designing a rudimentary spell checker of sorts. Suppose I have a div with the following content:

<div>This is some text with xyz and other text</div>


My spell checker correctly identifies the div (returning a jQuery object entitled
current_object
) and an index for the word (in the case of the example,
5
(due to starting at zero)).

What I need to do now, is surround this word with a span e.g.

<span class="spelling-error">xyz</span>


Leaving me with the final structure like this:

<div>
This is some text with
<span class="spelling-error">xyz</span>
and other text
</div>


However, I need to do this without altering the existing user selection / moving the caret / invoking methods that do so e.g.

window.getSelection().getRangeAt(0).cloneRange().surroundContents();


In other words, if the user is working on the 4th div in the
contenteditable
document, my code would identify issues in the other divs (1st - 3rd) while not removing focus from the 4th div.

Many thanks!

Answer

You've tagged this post as jQuery but I don't think it's particularly necessary to use it. I've written you an example.

https://jsfiddle.net/so0jrj2b/2/

// Redefine the innerHTML for our spellcheck target
spellcheck.innerHTML = (function(text)
{
  // We're using an IIFE here to keep namespaces tidy.

  // words is each word in the sentence split apart by text
  var words    = text.split(" ");
  // newWords is our array of words after spellchecking.
  var newWords = new Array;

  // Loop through the sentences.
  for (var i = 0; i < words.length; ++i)
  {
    // Pull the word from our array.
    var word = words[i];

    if (i === 5) // spellcheck logic here.
    {
      // Push this content to the array.
      newWords.push("<span class=\"mistake\">" + word + "</span>");
    }
    else
    {
      // Push the word back to the array.
      newWords.push(word);
    }
  }

  // Return the rejoined text block.
  return newWords.join(" ");
})(spellcheck.innerHTML);

Worth noting my usage of an IIFE her can be easily reproduced by moving that logic to its own function declaration to make better use of it.

Be aware you also need to account for punctuation in your spellchecking instances.

Comments