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>
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)!
This becomes more clear when you use console.dir instead, and explicitly expand the properties of the object:
In your particular case, don't log the attribute node but rather its contents, like name and value.