0

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>
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • So, of course, it works as expected on FireFox. Note to self - always check something other than Chrome 8-( – didntgoboom Oct 19 '21 at 20:19
  • @didntgoboom Firefox has pretty much the [same issue](https://i.stack.imgur.com/3c3Kb.png) - notice the `[ crossed="true" ]` on the `attributes` property of the div object that has been logged before the modification but expanded after :-) But yes, it does seem to render the first preview synchronously. – Bergi Oct 19 '21 at 20:32