John1984 John1984 - 2 years ago 80
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
) and an index for the word (in the case of the example,
(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:

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

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


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

Many thanks!

Answer Source

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.

// 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>");
      // Push the word back to the array.

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download