Exploring the DOM: JavaScript and HTML Interaction Explained


When I first started with web development, I kicked things off by making website clones using HTML and CSS. I noticed some sites had cool sections where clicking would show hidden HTML, and at first, I had no clue how to do that. But once I got the hang of JavaScript, I could create those interactive parts myself. Let's dive into the DOM and see how we can use JavaScript to interact with HTML.
What is DOM?
DOM stands for Document Object Model. DOM is a hierarchical representation of web pages, such as HTML attributes, tags, and text contents, is represented as nodes. The tree is composed as :
Elements : Represented as nodes, which can have attributes, child nodes, and event listeners.
Attributes : Key-value pairs that provide additional information about the elements.
Text Content : The text inside the element.
Suppose you have a HTML code with following code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Understanding DOM</title>
</head>
<body>
<h1>Hello Viewer</h1>
</body>
</html>
The browser will display Hello Viewer
when open inside the web browser.
Additionally, the browser will create DOM tree internally:
How does the DOM work?
When a web page is loaded, web browser creates a DOM tree internally for the HTML structure. The DOM is then used to :
Render the page : The browser uses the DOM to render the page’s layout and content.
Handle events : The DOM allow developers to attach event handlers and event listeners to attach some events and to handle the events.
Update the page : The DOM provides methods for updating the page’s content, layout and behavior.
Selecting and Modifying HTML Elements
The DOM offers a variety of properties and methods for interacting with and manipulating documents.
Let's look at an example to understand this. Suppose we have the HTML code above, and we want to select the h1
element.
const heading = document.querySelector("h1")
Using querySelector()
, we can select the h1
element.
Now, we want to change the content of the h1
element from Hello Viewer
to something else.
heading.textContent = "Please Like If You Understand the Concept"
Using textContent
we can change the text inside the h1
element.
Selecting HTML Elements
Just like querySelector()
, there are many methods to select the elements of HTML. Lets understand some of them.
getElementById()
:
When we have id of elements, we can use getElementById()
to select that element.
For instance,
const element = document.getElementById('idName')
getElementsByClassName()
:
When we have elements with same class name, we use getElementsByClassName()
.
For instance,
<div class="container"></div>
<div class="container"></div>
<div class="container"></div>
<script>
const containers = document.getElementsByClassName("container")
containers.forEach((container) => {container.textContent = "Hello, I a container"})
</script>
getElementsByClassName()
returns an array-like object of all child elements that have the specified class name(s). Therefore, we use the forEach()
method to go through each element and update the inner text of the container
.
querySelector() :
We already know how to use this, but we can select elements by their class names or IDs. This method returns the first Element
within the document that matches the specified CSS selector or group of CSS selectors. If no matches are found, it returns null
.
<div class="container" id="container-1"></div>
<div class="container" id="container-2"></div>
<div class="container" id="container-3"></div>
<script>
const container = document.querySelector(".container")
const container1 = document.querySelector("#container-1")
const container2 = document.querySelector("#container-2")
const container3 = document.querySelector("#container-3")
</script>
The syntax of querySelector()
is different. We use a dot followed by the class name to select an element and a hash symbol (#) followed by the ID to select an element.
querySelectorAll()
:
querySelectorAll()
returns a static (not live) NodeList
that represents a list of the document's elements matching the specified group of selectors. It works similarly to getElementsByClassName()
, and its syntax is the same as querySelector()
.
<div class="container"></div>
<div class="container"></div>
<div class="container"></div>
<script>
const containers = document.querySelectorAll(".container")
containers.forEach((container) => {container.textContent = "Hello, I a container"})
</script>
Modifying Elements
We can modify elements of HTML through JavaScript. Like creating new elements and appending it as a child node or modifying the inner text of element.
Modifying Text
To modify the text of element, we can use innerText
or textContent
. Both can change the text of element.
For instance,
<h1>Heading 1</h1>
<script>
const heading = document.querySelector("h1")
heading.textContent = "changing the heading"
console.log(heading.textContent)
heading.innerText = "changing back to heading 1"
console.log(heading.innerText)
</script>
Using these, we can modify the inner text of an element.
Appending an element inside an element
We can create an element and then append it inside another element.
For instance,
<div class="container"></div>
<script>
const h1 = document.createElement("h1")
h1.textContent = "I am Heading"
const container = document.querySelector('.container')
container.appendChild(h1)
</script>
To create an element, we use the createElement()
method. This method creates an element by specifying what to create. Then, we append the h1
element to the container using the appendChild()
method. This method adds the element to the end of the container (if there is more than one child).
These are some of the methods to select and modify the elements of HTML.
Changing the Style of Element
We can style the elements using JavaScript. To style the element we use style
property.
For instance, we create a div element which have border and background color using JavaScript.
To apply a border to the container
, use style.border = ""
, and to set a background color, use style.backgroundColor = ""
.
We can also add more styles, such as border radius and transitions.
Removing Elements using JavaScript
Just as we can create elements, we can also remove them using JavaScript.
removeChild()
:
To remove a child node, we use removeChild()
method.
For instance,
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>
<script>
let menu = document.getElementById('menu');
menu.removeChild(menu.lastElementChild);
</script>
How it works:
First, get the
ul
element with the idmenu
by using thegetElementById()
method.Then, remove the last element of the
ul
element by using theremoveChild()
method. Themenu.lastElementChild
property returns the last child element of themenu
.
lastElementChild
represents the last list in unordered list.
remove()
:
The Element.remove()
method removes the element from the DOM. It take no parameter and returns None(undefined)
For instance,
<div class="container" id="container-1"></div>
<div class="container" id="container-2"></div>
<div class="container" id="container-3"></div>
<script>
const container1 = document.getElementById("container-1")
container1.remove()
</script>
It remove container1
from the HTML.
Conclusion
Understanding the DOM is essential for web developers to create dynamic and interactive web pages. It allows manipulation of HTML elements using JavaScript. Mastering DOM techniques like selecting, modifying, styling, and removing elements can improve user experiences and make web applications more engaging. Exploring the DOM further opens up new possibilities in web development.
References
javascripttutorial : https://www.javascripttutorial.net/javascript-dom/
mdn : https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction
Subscribe to my newsletter
Read articles from himanshu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
