0

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

1 Answers1

1

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

colecmc
  • 3,133
  • 2
  • 20
  • 33