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

140
Views
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 answers
Answer question

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 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!