Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda