Attributes and Properties
Elements (nodes) of the DOM often have attributes and properties associated with them. Both values serve similar purposes and often have identical or similar names. The browser parses the HTML of the page and generates the DOM. Attributes will automatically be converted to their corresponding property (if one exists).
Note: Not every attribute has a corresponding property and vice-versa.
Attribute
When you write HTML you can add attributes to the tags themselves.
<input class="form-control" id="firstName" name="fName" type="text" size="55">
In the example above, there are five attributes on the input tag: class, id, name, type, and size
- There is a list of pre-existing attributes, however an attribute can be named anything that you want. The browser will always be able to parse and manipulate it.
- Attributes can be retrieved and set using the
getAttribute()andsetAttribute()methods in JavaScript.
Property
The DOM is just a JavaScript object so properties behave the same as with any object. They can be simple primitive values (number, string, boolean, etc.) or objects and methods.
// Sets (or overrides) the value of the id on the body tag.
document.body.id = 'body-tag';
document.body.foo = function() {
alert('bar');
}
// Opens an alert popup with 'bar' as the text.
document.body.foo();
Common Properties
innerText
You can fetch and alter the text value of any element through the innerText property.
const elem = document.querySelector('h1#page-title');
console.log(elem.innerText); // prints "Hello World"
elem.innerText = 'New Title';
console.log(elem.innerText); // prints "New Title"
classList
The classList property contains a list of the classes of the element. Classes can be added and removed using their respective methods (add and remove).
const listElem = document.querySelector('ul.main-menu');
listElem.childNodes.forEach((item, idx) => {
if(idx % 2 === 0) {
item.classList.add('even');
} else {
item.classList.add('odd');
}
});
style
Every element has a style property which contains all possible CSS properties. Individual properties can be accessed and set by addressing the property in the style object. Property names are camel case (ex: margin-bottom → marginBottom).
document.querySelectorAll('p').forEach(elem => {
elem.style.color = 'red'; // set the text color to red
elem.style.padding = '12px'; // add 12px of padding
elem.style.fontWeight = 'bold'; // bold the text
});
parentNode and children
const elem = document.querySelector('#main-menu > li');
// returns the parent of the specified element.
const parentElem = elem.parentNode;
// returns all immediate children of the specified element.
const childrenNodes = document.body.children;
Differences
- Attribute values are always strings, whereas properties have varied types.
- Property names are case-sensitive, whereas attribute names are not.