DOM Access in JavaScript

The JS Way to Utilize the DOM Web API

The API that provides access to the Document Object Model and allows us to take control of parts of the document. For more info on what comprises the DOM, check out MDN's writeup.

The example below performs multiple DOM manipulations. The CSS styling shown here can be done by the name (like .width(), for example) when available, or with style.name, like .style.margin = '0 auto'.

↓Example & darr;

function handleHTML() {

    document.getElementById('para1').align = 'center';

    document.getElementById('img1').src = 'https://source.unsplash.com/random/50';

    document.getElementById('img1').width = '50';

    document.getElementById('img1').style.margin = '0 auto';

setTimeout(handleHTML, 2000);

DOM Access

Here are commonly used parts of the DOM API

  • document.getElementById(id) - Returns an Element that matches the given ID.
  • document.getElementsByTagName(name) - Returns an an array-like object of elements in document order , called an HTMLCollection, that match the given tag name.
  • document.createElement(name) - Creates the HTML element defined by the tagName if the name is known. If it is not, an HTMLUnknownElement is created instead.
  • parentNode.appendChild(node) - Adds a node to the end of the list of children of the given parent node. If the child already exists, it will be moved from its current position to the new position.
  • element.innerHTML - Retrieves or sets the given HTML code.
  • element.style.left - Retrieves or sets the inline style of an element.
  • element.setAttribute() - Sets or updates the value of the given attribute on the element.
  • element.getAttribute() - Returns the value of the given attribute on the element.
  • element.addEventListener() - Begins monitoring a given event on a the element and will run a function when the event occurs.
  • window.content - Returns a Window object for the primary content window.
  • window.onload - processes load events on a Window, XMLHttpRequest, element, etc
  • window.scrollTo() - Scrolls to a specific place in the document.

DOM Data Types

Below are the different data types, also called interfaces, that are part of the DOM API.

  • Document: This object is the root document object itself.
  • Node: A Node is any object within the Document.
  • Element: An object reference to a node.
  • NodeList: An array of Nodes or Elements.
  • Attribute: Nodes that serve small, but special purposes.
  • NamedNodeMap: An array of Nodes that uses both names and an index for accessing the values. Despite there being an index, the nodes are not in a set order.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

↑ Back to Top