SpinSpire logo

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 at least similar names. The browser parses the HTML of the page and generates the DOM. Attributes will automatically be converted to their corrisponding property (if one exists).

Note: Not every attribute has a corresponding propery 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

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

  1. innerText
    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".
  1. classList
    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');
    }
    });
  1. style
    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
    })
  1. parentNode and children
    <body>
    <script>
    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
    </script>
    ...
    <ul id="main-menu">
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
    <li><a href="#four">Four</a></li>
    </ul>
    ...
    </body>

Differences

  1. Attribute values are always strings, whereas properties have varied types.
  2. Property names are case-sensitive, whereas attribute names are not.

References:
  1. W3 Schools: DOM Element Object