'localStorage error when trying to load content

I have a function to highlight words:

// This is to read previews highlights when user reload the page
var myContent = localStorage.getItem("text"); // it not highlight the previews texts
          for(var i = 0; i < myContent.rangeCount; i++) {
            highlightRange(myContent.getRangeAt(i));
          }




function myFunction() {
              var userSelection = window.getSelection();
              //localStorage.setItem("text", userSelection); // save to localstorage
              for(var i = 0; i < userSelection.rangeCount; i++) {
                highlightRange(userSelection.getRangeAt(i));
              }
}
    
    
    
    function highlightRange(range){
      span = document.createElement("span");
      span.appendChild(range.extractContents());
      span.setAttribute("style","background:#ffc570;");
      range.insertNode(span);
    }
<button type="button" id="myCheck" onClick="myFunction()";>Click to highlight</button>
<br>
<div>Some text to highlight</div>

I'd like to save at localstorage all the highlights to show again after user reload the page. The problem is that highlights disappear after I reload the page. What I am doing wrong?

(note that I comment the setItem just to make code snippet work cause localstorage is not allowed in it).



Solution 1:[1]

You can make an class that changes the background color to yellow and select that class using a javascript function!
HTML:

<div class = "highlight">Some text to highlight</div>
<button onclick = "highlight()">Click to highlight</button>

CSS:

.text_highlighted{
  background-color: yellow;
  height: fit-content;
  width: fit-content;
}

JS:

function highlight(){ 
    const text = document.querySelector('.highlight');
    text.classList.toggle("text_highlighted");
}

You can also check this on codepen: https://codepen.io/HaibaoM/pen/rNpQRMx
I hope it will help!

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 HaibaoM