Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"HTML attribute" versus "property of the DOM element" [duplicate]

I'm confused by the difference between "HTML attribute" and "property of the DOM element". From this post, I learned that getAttribute("class") returns the former, while element.className returns the latter. However, I could't understand the output of the following code:

var span = document.querySelector("#span");
console.log(span.className + ' ' + span.getAttribute("class"));
span.className = "bar";
console.log(span.className + ' ' + span.getAttribute("class"));
<span id="span" class="foo"><span>

I expect the result to be

foo foo
bar foo

because in my understanding the content of my HTML file hasn't been changed while javascript is run. Furthermore, when I replace the span.className = "bar"; line with span.setAttribute('class', 'bar');, same result remains.

My question is: What's the difference and relationship between "HTML attribute" and "property of the DOM element"?

like image 301
nalzok Avatar asked Dec 09 '25 04:12

nalzok


1 Answers

To confuse matters further, the HTML5 spec refers to them as content attributes, and IDL attributes respectively.

They are sometimes associated by the same names, and sometimes not.

In the most common type of association, the two types of attribute are said to "reflect" each other, so that when one changes so does the other. HTML5 describes this in Reflecting content attributes in IDL attributes. The first paragraph says:

Some IDL attributes are defined to reflect a particular content attribute. This means that on getting, the IDL attribute returns the current value of the content attribute, and on setting, the IDL attribute changes the value of the content attribute to the given value.

Sometimes the IDL attribute and the content attribute which reflect one another have different names. For example, the input "value" content attribute is reflected by the defaultValue IDL attribute.

Sometimes the association between the two is more complex; changes to one may affect the other but not be a direct one-to-one mapping.

like image 96
Alohci Avatar answered Dec 10 '25 17:12

Alohci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!