DEV Community

Cover image for Understanding the DOM: A short guide to web pages structure
Isinkaye Praise
Isinkaye Praise

Posted on

Understanding the DOM: A short guide to web pages structure

DOM, which stands for Document Object Model is a representation of a document (HTML) in a hierarchical form. It portrays a document using a tree-like model. Each element is viewed as an object and is related to other elements as parent or child. When writing HTML codes, there are elements that are placed under/within other elements. For example, an input element could be placed within a div tag. The Div tag acts as the parent while the input tag is the child. It should be noted that a parent element can have more than one child element in it.
The illustration of the hierarchy level which DOM gives also makes it easy to manipulate the information and styles in an HTML document using a programming language like JavaScript or Python. The DOM gives accessibility to the element as an object, the properties, methods and events of the element.
The document and its components are represented as nodes with the document itself as the parent nodes and the components as child nodes. These components could be elements, attributes or text contents.
As mentioned earlier, JavaScript, which is a scripting language, can be used to manipulate DOM. It has defined methods that can select any element using the tag name, class name or the id name. Using an example, I will be explaining how to select HTML elements.
Const elementName = document.getElementById(“idName”). This line uses an ID name to select.
Const elementName = document.getElementsByClassName(“className”) . Using classnames

Note that the code for ID has element while that for ClassName has elements. This is because an ID name can only refer to one element while ClassName can be used for a bunch for element with similar style. There are also other ways to find elements such as: getElementByTagName, querySelectorAll and others.
Using a step-by-step guide, I will be demonstrating how to add a “p” element to an existing Div tag with a class name of “div”.

  1. First step is to select the existing div element. const bigDiv = document.getElementsByClassName("div")
  2. Next step is to create a p element const paragraph = document.createElement("p")
  3. Then, create a text which will be in the paragraph const newText = document.createTextNode("This is a paragraph.")
  4. Append the formed text to the paragraph paragraph.appendChild(newText)
  5. Append the paragraph to the existing div bigDiv.appendChild(paragraph)

I hope this short article is able to break down what DOM means and how it can be used. For more information, you can check out “W3Schools” or “MDNDocs”.

Top comments (0)