简体   繁体   中英

How to insert Node based on css class in JS?

I have this code that highlights the text selection. It wraps the text that was selected within a passage and then adds <span style='background:yellow'> text selected </span> I want to accomplish the exact same task, but instead, do this:

<span class='blue_mark'> text selected </span>

How can I accomplish this within the following code:

var selection = document.getSelection();
  var range = selection.getRangeAt(0);
  var contents = range.extractContents();
  var node = document.createElement('span');
  node.style.backgroundColor = "yellow";
  node.appendChild(contents);
  range.insertNode(node);
  selection.removeAllRanges(); //Clear the selection, showing highlight

If you just want a class instead of a style attribute, use this by replacing node.style. backgroundColor = "yellow"; node.style. backgroundColor = "yellow"; with node.classList.add('blue_mark'); or node.className += ' blue_mark'; .

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