DOM DOM DOM DOM DOM

Colten Appleby
3 min readApr 22, 2021

A Domain Object Model or ‘DOM’ in its simplest form is a Tree Data Structure. It is made up of HMTL and can accessed by Javascript to be read, manipulated, and for new information to be pushed onto the webpage. If you have ever taken a course in algorithms, then you know that a tree in programming is actually upside down. Also, you may know that each branch or leaf is called a node. That is the same for the DOM.

Nodes

  1. The top node is called the root node.
  2. All non-root nodes have a parent node.
  3. Parent nodes have children.

DOM Example:

DOM

Accessing the DOM

To access the nodes on DOM with Javascript you can use a built in function such as “querySelector.” See the below code block to see it in use.

document.querySelector("div#character-bar")
  1. Document is used to gain access to the DOM
  2. QuerySelector is the function to search and select elements on the document. It will select the first item that satisfies it’s parameters from item 3.
  3. The string is what you are selecting. The first part would be the element type; such as a form or a div, or a h1 (header). A ‘#’ is for an ID and a class is a ‘.’
  4. If nothing satisfies the parameters then querySelector will return null.

Traversing the DOM

Selecting our characterInfo div would allow us to view and manipulate its attributes

div = document.querySelector("div.characterInfo")

Typing div into the console would return this

div

Note that if you were to do “div#characterInfo” then javascript would return null because an id with characterInfo does not exist.

To access its children we would do

div.children

Which would return an HTMLCollection. Note there is only one child element.

To select its child we could do:

div.children[0]

We can continue to daisy-chain these together to select the form:

div’s child’s children
div.children[0].children[3]

One way to iterate through the children would be to use the ‘.nextElementSibling’ or the ‘.previousElementSibling’.

div.children[0].nextElementSibling

A note on Nodes:

There are other ways to select the the only child of our div. You can use a querySelector! Reminder that since ‘detailed-info’ is an id we use the ‘#’. Also note that we aren’t querying the entire DOM but instead just the div. We could use either but I prefer querying the div in this case to keep our logic cleaner.

detailedInfo = div.querySelector("div#detailed-info")

This would return:

Nodes:

  1. The <p> with id = ‘name’ is the first child node
  2. The <p> with id = ‘name’ has many siblings such as the <img>, the <h4>, and the <button>
  3. The <p>’s parent node is the <div> with the id of “detailed-info.”
  4. The <form> with id of “update-name-form” is the last child.

--

--