It's said by this article that one of the important reasons for HTML properties to be reflected back to the DOM is because CSS selectors rely on attributes, but why's that? This could be done without the reflection based on the spec.
For people who don't know what I'm talking about, read below:
In browsers, CSS selectors rely on attributes to work.
#myButton[someAttribute] {
opacity: 0.5;
font-weight: bold
}
So in our JavaScript if we change the property of an element, eventually we have to reflect it to the HTML DOM as well like this:
// we have changed some property
myButton.someAttribute= true;
// but this is not adequate, we need to reflect as well
myButton.setAttribute('someAttribute', '');
so we get this:
<button id="myButton" someAttribute></button>
not this non-reflected button:
<button id="myButton"></button>
In the HTML DOM, an Attr object represents an HTML attribute. An HTML attribute always belongs to an HTML element.
What is the reason for avoiding the attributes property in the HTML DOM? Explanation: When a web page is loaded, the browser creates a Document Object Model of the page. The reason for avoiding the attributes property in the HTML DOM is because Attributes don't have attributes.
The attributes have a data type of string. So no matter the value of the attribute, it will always return a string. Property: In contrast to the attributes, which are defined in HTML, properties belong to the DOM. Since DOM is an object in JavaScript, we can get and set properties.
Not all DOM properties map to attributes. The ones that do reflect to and from attributes, do so to maintain parity with the document language — in this case, HTML, which only has a concept of attributes, which as you've correctly pointed out is relied on by Selectors.
If attribute selectors mapped directly to DOM properties without the DOM discriminating between attribute properties and other kinds of properties, then attribute selectors such as the following would match, even though none of these exist as attributes in HTML:
[classList]
[className]
[dataset]
[offsetLeft]
[offsetTop]
[offsetWidth]
[offsetHeight]
... as well as [someAttribute]
matching elements with your non-existent someAttribute
as a property even when you don't reflect it with setAttribute()
.
In fact, this is exactly why label[htmlFor]
incorrectly matches label[for]
elements in Internet Explorer 7, even though the for attribute in HTML is simply called for
, not htmlFor
— the DOM uses htmlFor
to make up for the fact that for
is a reserved word in many languages including JavaScript, the main DOM scripting language, preventing it from being used as a property ident.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With