Introduction to the DOM

The power of JavaScript is its use in dynamically displaying and manipulating elements on a webpage written in HTML. We know that an HTML page consists of elements such as <head><body> <h1> tags or text fields and buttons. The DOM or Document Object Model represents the structure of these elements as a "tree" data structure after your web browser reads a page. The DOM Application Programming Interface (API) contains methods that provide JavaScript access to these elements. Start by reading this article to learn about the document structure of the DOM and how to find, create and change elements.

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.