Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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).

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!