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

142
Vistas
javascript DOM out of sync?

I'm playing with JavaScript and DOM for a (high school) class I'm teaching. Emphasizing that students use console.log for diagnostics. However, in using it I find the values retrieved from the DOM to be out of sync with the UI.

In the SSCE below, when the LI element is clicked, the first time it should log that the style is "color:red;", but it says style is "text-decoration:line-through;". I added the alert() to give time for anything async to finish but no joy.

If I remove the if( isOn ) clause, the attributes print out as expected, and after the first click attributes also print out as expected.

Guessing there's some synchronizing that needs to happen, just not sure what it may be ...

var theLi = document.getElementById("here");
theLi.addEventListener("click", crossOff);
theLi.setAttribute("style", "color:red;");
theLi.setAttribute("crossed", "off");

function crossOff(element) {
  var isOn = this.getAttribute("crossed") == "on";
  var attrs = this.attributes;

  for (const attr of attrs) {
    console.log(attr);
  }

  alert("huh??");

  if (isOn) {
    this.setAttribute("style", "text-decoration: none;");
    this.setAttribute("crossed", "off");
  } else {
    this.setAttribute("style", "text-decoration: line-through;");
    this.setAttribute("crossed", "on");
  }
}

//Write function crossOff here.
<!DOCTYPE html>
<html>

<body>
  <h3>To Do List:</h3>
  <ul>
    <li id=here>Eat</li>
  </ul>

  <script>
  </script>
</body>

</html>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem would be that you are logging attribute nodes, which are still linked to the DOM. The console is known to render its output asynchronously, as well as to display DOM elements in a "user-friendly" representation - notice you can even edit them just like in the DOM inspector ("Elements" panel)!

enter image description here

This becomes more clear when you use console.dir instead, and explicitly expand the properties of the object:

enter image description here

In your particular case, don't log the attribute node but rather its contents, like name and value.

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