Skip to main content

HTML attribute vs DOM property

  • HTML is a language, DOM is an object model that browsers use in order to represent the structure of the page.

  • Attribute is said in the context of the HTML page structure, whereas DOM properties are said in the context of DOM object.

  • Attribute is said in the perspective of HTML language whereas the property is said in the perspective of JavaScript language.

  • HTML is given by server and DOM is generated by browser based on the HTML page structure

  • HTML attributes can be modified from HTML as well as JavaScript, where as DOM properties can be accessed primary from JavaScript.

  • HTML attribute names are generally hyphenated and lower-case words; DOM properties are always camel-cased.

  • Most of the HTML attributes have the corresponding DOM property names (one to one correspondence); But some of them need a different approach to access through JavaScript

    • CSS classes are added in HTML through class attribute; They can then be accessed or manipulated through [element].classList (.add(), .contains(), .remove())
    • Data attributes are added in HTML through data-* attribute; Then can then be accessed or modified through [element].dataset.[camelCasedAttribute].
  • Modifying DOM properties will immediately reflect in the page; Modifying HTML attributes through setAttribute may not always work this way. Good example for this is <input> element's value. An input element's value attribute only sets its default value, updating it through JavaScript using setAttribute will not make the actual value change. Use [element].value property to change the actual value.

  • All HTML elements must be given values and they can be strings only; Some DOM properties may exist in HTML without a value assigned. Classic example is disabled attribute. Also note that disabled state cannot be assigned by using setAttribute to actually disable or enable it; instead, use the .disabled prop and assign true or false to affect it in JavaScript.

More reading:#

https://dotnettutorials.net/lesson/html-attribute-vs-dom-property/

Last updated on