DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • Custom Elements Manifest: The Key to Seamless Web Component Discovery and Documentation
  • React Server Components (RSC): The Future of React

Trending

  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • A Guide to Container Runtimes
  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  1. DZone
  2. Coding
  3. Languages
  4. Understanding DOM (Document Object Model)

Understanding DOM (Document Object Model)

Discover the power of the Document Object Model (DOM) and learn about how to use it to manipulate web pages with JavaScript.

By 
Shashank Sharma user avatar
Shashank Sharma
·
Mar. 16, 23 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
2.0K Views

Join the DZone community and get the full member experience.

Join For Free

Contents

  1. Introduction to the Document Object Model

  2. What is the DOM?

  3. How does DOM work?

    • The tree structure of the DOM

    • Nodes and Elements

    • properties

    • Methods

  4. Selectors

Introduction

  • In this blog, we are going to dive deep into DOM and try to understand what it is and how it works.

What Is DOM?

  • It acts as an interface for HTML and XML documents, which represent the content of the document as a tree-like structure.
  • DOM allows JavaScript and other programming languages to interact with and manipulate the content and structure of HTML or XML documents.
  • We can use DOM to add or remove elements from the page, change the text of elements, or responds to a mouse click or keyboard inputs.

How Does DOM Work?

  • When a web page is loaded, the browser creates a Document Object Model (DOM) of the page.
  • DOM works like a tree structure and converts the HTML code into a tree in which each node represents the elements of that particular HTML code.
  • The root of this tree is document objects, and each node represents elements like paragraphs, images, headers, links, etc.
HTML
 
<html>  
  <head>    
    <title> DOM BLOG </title>  
  </head>  
  <body>    
    <button> Click here to read the blog </button>  
  </body> 
</html>


  • For example, if the above code is simple HTML code, then what DOM will do is convert this code into a tree-like structure so that the DOM manipulation can be done easily.
  • Below is the image of how the above code gets converted into a tree structure by DOM.how the above code gets converted into a tree structure by DOM
  • In DOM, properties and methods are two types of members associated with each node or element, or object. Properties and methods, along with some attributes and functions, help in interacting with and manipulating the HTML to get the desired outcome.
  • Let's understand properties and methods with the example:

The Properties

Let's say you have an HTML document with a heading element like this:

HTML
 
<h1 id="blog-head">It's a blog about DOM</h1>


Now, if we want to change this heading without even touching HTML, then what we are going to do is use DOM.

First, we “get” this heading element in JavaScript using a selector called getElementbyID(” ”);

It returns the value as an object.

JavaScript
 
var heading = document.getElementById('blog-head');


Then we access its inner HTML using .innerHTML and change its value/text accordingly.

JavaScript
 
heading.innerHTML = 'Read, Learn and Leave your Feedback!';


By doing all these steps, We change the innerHTML of the heading without even touching HTML.

Don't worry; we are going to learn selectors in just a few minutes.

The Methods

Let's say you have a button element in your HTML document like this:

HTML
 
<button id="my-button">Click me to read the blog about DOM</button>


Now, same as above, first, we select the button in JavaScript using a selector called .getElementsbyID(” ”).

It returns the value as an object.

Now, we can manipulate and make changes with the button without touching HTML. Let’s say we want an alert of “You clicked the button for reading the blog about DOM!” whenever a user clicks the button.

In order to do that, we need to do two things.

  1. Add event listener, which responds to the click

  2. A function()that executes the block of code and returns the alert which says, “You clicked the button for reading the blog about DOM!”.

JavaScript
 
var button = document.getElementById('my-button'); button.addEventListener('click', function() {  alert('You clicked the button for reading the blog about DOM!'); });


This .addEventListener() is what we call a method in DOM. We passed two arguments in it.

  1. click = then click on button

  2. function() = which shows the alert when the click happens.

NOTE: Methods have parenthesis() at the end, and properties do not. 

In summary, properties are the value of an element or node, or object, while methods are similar functions() as it has a code that gets executed when that particular method is called.

There are differences b/w methods() and functions(), but it's not the topic of this blog.

Selectors

There are many ways to select elements inside DOM.

Let's say we have this HTML code:

HTML
 
<ul id = title>  <li class = item> One <li>  <li class = item> One <li>  <li class = item> One <li> </ul>


Now, if we want to select the li we use selectors:

1) get Elements by Tag Name(””);

  • This Selector selects all the elements by their tag names(li, ul, p, h1, h1 etc…)

  • In this case, we are selecting li

  • This selector selects all the li in the HTML document

JavaScript
 
document.getElementsbyTagName("li"); // HTMLCollection(3) [li.item, li.item, li.item] => Selects all 3 "li" from above HTML code


NOTE: Elements is plural, so it returns more than one value in form of an array.

Now, Let's style the li

JavaScript
 
document.getElementsbyTagName("li"); document.getElementsbyTagName("li")[0].style.color = "Red"; //change color of first li to red document.getElementsbyTagName("li")[1].style.color = "Blue"; //change color of second li to Blue document.getElementsbyTagName("li")[2].style.color = "Green"; //change color of Third li to Green


We can also change the text size and text style by using different properties in place of style.

You can change the style of all three elements at once using loops.

JavaScript
 
var items = document.getElementsByTagName("li"); for (let i = 0; i < 3; i++) {  items[i].style.backgroundColor = "red"; }


2) get Elements by Class Name(””);

  • This selector selects all the elements with particular class names given to that element.
HTML
 
<ul id = title>  <li class = item> One <li>  <li class = item> One <li>  <li class = item> One <li> </ul> <button class="btn">Click to read blog</button>


JavaScript
 
document.getElementsbyClassName("btn"); //This selects all the elements with .btn class in it


  • Similar to the above example, we can also add different properties to get different results, like changing text color, text size, and others.
JavaScript
 
document.getElementsByClassName("btn"); document.getElementsByClassName("btn")[0].textContent = "you are reading the blog" //This changes the text content inside the button.


  • This selector also returns the value as an array.

3) get Element by ID(” ”);

  • This selector selects the element with the Unique ID given to it.
HTML
 
<ul id = title>  <li class = item> One <li>  <li class = item> One <li>  <li class = item> One <li> </ul> <button class="btn">Click to read blog</button>


Now, let's select the ul element using its ID.

JavaScript
 
document.getElementbyID("title"); //Selects element with ID Only


JavaScript
 
document.getElementbyID("title").style.color = "red"; //Styles the title element and changes its color to Red.


NOTE: ID selector has “Element” without "s," which means it's singular, so it returns only a single value.

Also, ID is a unique property, and on every page, there is only one ID of the same name, so that also clears that there’s only one single element with a particular ID.

4) query Selector(””);

  • So, the previous three selectors are used in specific cases(for the tag name, for class, for ID). But, in the query selector, we can target any element with its name only, whether it be h1,h2,h3, or IDs like(#title) or classes like(.btn)

HTML
 
<h1 class = "header" id = "first-head">Follow me for more such informative blogs</h1>


  • We can style and manipulate the h1 element in three ways here;
JavaScript
 
document.querySelector("h1").style.color = "red" //Here we select the element with its tag name //This changes color of element to Red


JavaScript
 
document.querySelector("#first-head").style.color = "Blue" //Here we select the same element with its ID //This changes color of element to Blue


JavaScript
 
document.querySelector(".header").style.color = "Green" //Here we select the same element with its class name //This changes color of element to Green


This is all for this blog. Read, learn, and leave your important feedback so that I can improve my future blogs. There is going to be one more part of this blog, so stay tuned for that one.

Document HTML JavaScript Object model

Published at DZone with permission of Shashank Sharma. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • Custom Elements Manifest: The Key to Seamless Web Component Discovery and Documentation
  • React Server Components (RSC): The Future of React

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!