Milos Milos - 2 months ago 19
HTML Question

How to check if selected text in html already has a class?

I'm making a function that takes a selected piece of text and highlights it by adding the tag. It highlights the text but if I click the highlight button again, the text disappears. Instead, I'd just want the text to go back to being un-highlighted. Anyone have suggestions how I could go about doing this?



highLightText() {
var selection = window.getSelection();
console.log('this is the selection: ', selection);
var selection_text = selection.toString();

var mark = document.createElement('mark');

mark.textContent = selection_text;

var range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(mark);
}





My idea was to somehow check if the selected text from var selection has an element named mark in it and if it does, don't continue with the rest of the function. I'm just not exactly sure how to implement it.

Answer Source

You can get a reference to the node that is currently selected by using the Selection's anchorNode or focusNode and from there get the parent element of the text.

var parent = selection.anchorNode.parentElement;

From there is it just a matter of checking it's nodeName property to see if it is mark.

parent.nodeName == "MARK" //nodeName is uppercase

After that just replace the mark element with the text node and call normalize() on the grand parent element to make sure any adjacent text nodes get merged

let grandParent = parent.parentElement; 
parent.replaceWith(document.createTextNode(parent.textContent));
grandParent.normalize();

This will do all the text in the mark element and not just the selected text of a mark, for that you will have to modify the code if that was the intention.

Demo (hit any key after making a selection)

function highLightText() {
  var selection = window.getSelection();
  var parent = selection.anchorNode.parentElement;
  var selection_text = selection.toString();

  if (parent.nodeName == "MARK") {
    let grandParent = parent.parentElement;
    parent.replaceWith(document.createTextNode(parent.textContent));
    grandParent.normalize();
    return;
  }

  var mark = document.createElement('mark');

  mark.textContent = selection_text;

  var range = selection.getRangeAt(0);
  range.deleteContents();
  range.insertNode(mark);
}
document.addEventListener('keyup',highLightText);
<div>
  <div>Test one two three</div>
  <div>Test four five six</div>
  <div>Test seven eight nine</div>
  <div>Test ten eleven twelve</div>
</div>