'How can I keep the text highlighted with JS?

I'm working on a conceptual project. Text reaveal on selection with highlight.

I have to keep the text highlighted once it is selected.

<div class="reveal" id="textToSelect"> 
    <span class="reveal-text">texttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttext</span>
    <span class="reveal-text">Ctexttexttexttexttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttext</span>
</div>

I used execommand to create some spans with background-color on selection. It's work but execommand is now obsolete.

document.getElementById('textToSelect').addEventListener('mouseup', function() {
sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
  range = sel.getRangeAt(0);
}

document.designMode = "on";
if (range) {
  sel.removeAllRanges();
  sel.addRange(range);
}

document.execCommand("hiliteColor", false, "red");

document.designMode = "off";
});

How can I create those spans without execCommand ? I see answer but maybe too general for this speficic case.

Many thanks in advance for your support !



Solution 1:[1]

Is the following your expected behaviour on mouse over the #textToSelect?

#textToSelect .reveal-text {
  background-color: #ddd;
  cursor: pointer;
}

#textToSelect:hover .reveal-text {
  background-color: yellow;
}
<div class="reveal" id="textToSelect"> 
    <span class="reveal-text">texttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttext</span>
    <span class="reveal-text">Ctexttexttexttexttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttext</span>
</div>

Solution 2:[2]

If you need to change the color once clicked, you need to add this to your reveal-text class, so in your css file add this:

a:active {
  color: red;
}

change the color accordingly.

Solution 3:[3]

Another option would be to have a class for the specific change you want and toggle it with the classList property in JavaScript.

Example:

var x = document.querySelector('.text-color');

x.onclick = function() {
  console.log('active');
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abin Thaha
Solution 2 Ziya Yektay
Solution 3 JDevenyi