简体   繁体   中英

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?

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>'
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM