Introduction to the DOM

Some element attributes, such as href for links, can be accessed through a property of the same name on the element's DOM object. This is the case for most commonly used standard attributes.

But HTML allows you to set any attribute you want on nodes. This can be useful because it allows you to store extra information in a document. If you make up your own attribute names, though, such attributes will not be present as properties on the element's node. Instead, you have to use the getAttribute and setAttribute methods to work with them.

<p data-classified="secret">The launch code is 00000000.</p>
<p data-classified="unclassified">I have two feet.</p>

<script>
  let paras = document.body.getElementsByTagName("p");
  for (let para of Array.from(paras)) {
    if (para.getAttribute("data-classified") == "secret") {
      para.remove();
    }
  }
</script>

It is recommended to prefix the names of such made-up attributes with data- to ensure they do not conflict with any other attributes.

There is a commonly used attribute, class, which is a keyword in the JavaScript language. For historical reasons – some old JavaScript implementations could not handle property names that matched keywords – the property used to access this attribute is called className. You can also access it under its real name, "class", by using the getAttribute and setAttribute methods.