JavaScript HTML DOM

Antonio Caballes
2 min readJun 4, 2023

--

Document Object Model is the representation of the objects of an HTML document or XML document.

Document refers to the file.

Object refers to the element tags.

Model pertains to the file structure.

DOM is a programming interface or an API. API is commonly use with JavaScript. In addition, DOM makes it easy to read and access and update the content of HTML or XML document.

HTML DOM allows JavaScript to change the content of HTML elements.

In this example, I created a basic HTML DOM function in JavaScript.

This examples changes the content of the mentioned elements.

The innerHTML is used to change the content.

There are functions used to get the element and a sent of elements such as the:

  1. getElementById
  2. getElementsByClassName
  3. getElementsByTagName

Code

<div class="container">
<div class="row justify-content-around py-5">
<div class="col-6 border border-black">
<h1 id="demo" class="display-4">A Paragraph</h1>
<p class="section">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Modi pariatur facere
perferendis tempora commodi eos dolores veniam iure</p>
<p class="section">ncidunt quisquam! Mollitia, nisi exercitationem rerum modi eos possimus aliquam ex
dolores.</p>
</div>
<div class="col-5 d-flex align-items-stretch">
<button type="button" class="btn btn-info flex-fill" onclick="myFunction()">Change Header</button>
<button type="button" class="btn btn-danger flex-fill" onclick="makeItRed()">Make it red sections</button>
<button type="button" class="btn btn-success flex-fill" onclick="myButtons()">Disable buttons</button>
</div>
</div>
</div>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
// Make all class "section" red
function makeItRed() {
const nodes = document.getElementsByClassName("section")
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.color = "red"
}
}

function myButtons() {
const buttons = document.getElementsByTagName("button")
for(let i = 0; i < buttons.length; i++) {
buttons[i].classList.add("disabled")
}
}

Both getElementsByClassName and getElementsByTagName returns a collection of data.

The reason for using a for loop is because of the HTML collection that is stored in the “nodes” and “buttons” variable are array-like or list of HTML elements.

By pressing the button “Make it red sections” you will have:

Result

Every web browser uses DOM to make web pages accessible like JavaScript.

--

--