technically, I just assigned one variable to the other, both lines. Why are the meanings different?
Because yes, innerHTML is special. This is not just a value property, it is an accessor property. When you assign it, you call the under-covers function, which parses the HTML code you give it and creates the necessary DOM nodes and elements. When you read its value, you call another function under-covers, which repeats itself through the DOM tree, starting from the element that you are accessing it, and builds an HTML string representing this DOM tree.
So, while you assigned it the character U + 00A0, which received the converted text from the DOM node; and when you read from it, this DOM node text was displayed as canonical (for each browser rule) HTML line: .
You can see that innerHTML is not just a value property, using the DOM to control the element:
var target = document.getElementById("target"); target.innerHTML = "\u00A0"; console.log(target.innerHTML);
<div id="target"></div>
Note that it is also possible to define access properties in JavaScript objects; it's not just a DOM that can have them:
var o = { get foo() { console.log("foo getter called"); return this._foo; }, set foo(value) { console.log("foo setter called"); this._foo = value; } }; console.log("foo: " + o.foo); o.foo = 42; console.log("foo: " + o.foo);
The fact that innerHTML is a property with a getter and setter, so code like this is bad practice:
for (var n = 0; n < something.length; ++n) { element.innerHTML += ", " + something[n]; }
This constantly creates and then destroys and restores the DOM tree and makes a bunch of hidden function calls. Instead, you should build a string, and then assign it.
source share