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.
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: