DOM Element Attributes

There are multiple ways1 to set and remove attributes on HTML DOM Elements:

  1. element.attributes2

The Element.attributes property returns a live collection of all attribute nodes registered to the specified node. It is a NamedNodeMap, not an Array, so it has no Array methods and the Attr nodes’ indexes may differ among browsers. To be more specific, attributes is a key/value pair of strings that represents any information regarding that attribute.

  1. element.getAttribute3 and element.setAttribute4

The setAttribute() method sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

The getAttribute() method of the Element interface returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or “” (the empty string); see Non-existing attributes for details.

  1. Properties on the DOM Element5 object, for example element.id6 or element.className7

The id property of the Element interface represents the element’s identifier, reflecting the id global attribute.

The className property of the Element interface gets and sets the value of the class attribute of the specified element.