Vivek Chandraprakash
Vivek Chandraprakash

Reputation: 1163

How to add a tag to a word inside a div using javascript

i'm trying to create a spellchecker using javascript. I'm using a div tag as input control for this purpose.

how do I add tags to the misspelt words using javascript?

is there a way to add tags only to selected words instead of completely refilling the div?

Upvotes: 0

Views: 376

Answers (1)

HBP
HBP

Reputation: 16033

You mst replace each misspelt words with a new tag, a SPAN is probably the most convenient, which can specify a class to target your CSS.

function mispelt (el, word, class) {
  // replaces all occurrences of the string 'word' in the element
  // 'el' with a span which has a class 'class'
  // Assumes 'word' contains no regexp special chars 

  el.innerHTML = el.innerHTML.replace (
      RegExp ('\\b(' + word + ')\\b', 'ig'),
      '<span class"' + class + '">$1</span>'
    );
}

Upvotes: 3

Related Questions