Highlighting user selected text using javascript

726 Views Asked by At

The issue I'm facing is when user selects any text it should get highlighted, so we are trying to fetch the DOM elements of that text using window.getselction and wrap them in <span> with styling to add background color. It works fine for most of cases, but when selecting list items if we select only one list item then the content inside that <li> tag is wrapped in our span and it is working fine, the issue is on selecting multiple <li> items then this span tag messes the html of the list and I dont get desired output.

function handleSelectedText() {
    var parentOfSel;
    if (typeof window.getSelection != "undefined") {
      parentOfSel = window.getSelection().getRangeAt(0)
    }
    var deviation = document.createElement("span");
    deviation.style.backgroundColor = "cyan";
    deviation.id = "some-id-to-identify-sapn";
    deviation.appendChild(parentOfSel.extractContents());
    parentOfSel.insertNode(deviation);
  }

This function triggers on mouseUp event.

Open to use any package if exits for this as it is being implemented in React JS.

1

There are 1 best solutions below

2
On

As today's web application running in a browser with CSS3 support, the ::selection selector can match your requirement by doing things easily like this:

::selection { background-color: cyan }

::selection {
  background-color: cyan;
}
<p>Unordered list:</p>

<ul>
  <li>First item</li>
  <li>Second item</li>
  <li>Third item</li>
<ul>