JS DOM - 01.05 - Attributes Properties

When the browser loads the page, it “parses” the HTML and generates DOM objects from it. For element nodes, most standard HTML attributes automatically become properties of DOM objects.

For instance, if the tag is <body id="page">, then the DOM object has body.id = "page".

  • Attributes – is what’s written in HTML.
  • Properties – is what’s in DOM objects.

DOM properties

document.body,myData = {
	name: 'ceasar',
	title: 'imperator'
};

alert(document.body.myData.title);   // imperator

Methods can be added

document.body.sayTagName = function() {
	alert(this.tagName);
};

document.body.sayTagName();   // Body

So, DOM properties and methods behave just like those of regular JavaScript objects:

  • They can have any value.
  • They are case-sensitive (write elem.nodeType, not elem.NoDeTyPe)

HTML attributes

In HTML, tags may have attributes.
When the browser parses the HTML to create DOM objects for tags, it recognizes standard attributes in HTML and creates DOM properties from them.

So when an element has id or another standard attribute, the corresponding property gets created. But that doesn’t happen if the attribute is non-standard.

A standard attribute for one element can be unknown for another one. For instance, "type" is standard for <input>, but not for <body>

All attributes are accessible by using the following methods:

elem.attributes 
- a collection of objects that belongs to `attr` class with `name` and `value` properties.  (is iterable)

elem.hasAttribute(name)  // checks for existence.
elem.getAttribute(name) // gets the value.
elem.setAttribute(name, value)  // sets the value.
elem.removeAttribute(name)  // removes the attribute.

[[2.3 class, attributes#Editing HTML attributes|Editing Attributes]]

HTML attributes have the following features:

  • Their name is case-insensitive (id is same as ID).
  • Anything can be assigned, Their values are always strings.
<body id="test" something="non-standard">
	<script>
		alert(document.body.ID);  //  test     case insensitve
		alert(document.body.something);  // undefined

		alert(document.body.getAttribute('something'));  // non-standard
	</script>
</body>


<body>
	<div id="elem" about="Elephant"></div>

	<script>
		alert( elem.getAttribute('About') );  //  Elephant   case insensitve
		
		elem.setAttribute('Test', 123);  // 123 becomes a string

		alert( elem.outerHTML );  // checking added attribute
		
		for(let attr of elem.attributes ) {
			alert( `${attr.name} = ${atr.value}` );
			}
	</script>
</body>
Property-attribute synchronization
DOM properties are typed

DOM properties are not always strings.
input.checked property of check boxes is a boolean.
style attribute is a string in HTML, but the style property is an object.