The Wayback Machine - https://web.archive.org/web/20250404095931/https://www.geeksforgeeks.org/javascript-html-dom/
Open In App

JavaScript HTML DOM

Last Updated : 28 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The JavaScript HTML DOM (Document Object Model) is a powerful tool that represents the structure of an HTML document as a tree of objects. It allows JavaScript to interact with the structure and content of a webpage. By manipulating the DOM, you can update the content, structure, and styling of a page without requiring a page reload.

What is the JavaScript HTML DOM?

The JavaScript HTML DOM is an interface that allows programs to interact with web pages.

  • It provides a structured way to represent the document’s elements as objects.
  • Using JavaScript, developers can access, modify, or delete HTML elements on the webpage, enabling dynamic content updates.

Features of JavaScript DOM

  • Tree Structure: The DOM is organized like a family tree, with elements that have parent-child relationships. It is easy to find and change things based on their positions.
  • Element Access: You can use different methods like getElementByIdgetElementsByTagName, and querySelector to access specific elements on a webpage

What is HTML DOM?

  • HTML DOM stands for HTML Document Object Model.
  • It is a programming interface for web documents.
  • It represents the structure of an HTML document as a tree of objects.
  • With the HTML DOM, JavaScript can access and manipulate all elements of an HTML document.

Example: This example shows the accessing the JavaScript HTML DOM by id.

HTML
<html>
<head></head>

<body>
    <h1 id="demo">This is some text.</h1>
    <button onclick="changeText()">
      Change Text
      </button>

    <script>
        function changeText() {
            let element = document.getElementById("demo");
            element.textContent = "Text changed by JavaScript!";
        }
    </script>
</body>

</html>

In this example

  • The useState hook is used to create a state variable subject and a function setSubject to update its value.
  • The handleInputChange function updates the subject state whenever the user types in the input field.
  • The value entered in the input field is dynamically displayed below it as the state updates.

Output

Output
JavaScript HTML DOM

Accessing Elements in the DOM

getElementById()

Retrieves an element by its id.

let heading = document.getElementById("title");
console.log(heading.textContent);

getElementsByClassName()

Returns a collection of elements with a specified class.

let items = document.getElementsByClassName("list-item");
console.log(items[0].textContent);

getElementsByTagName()

Selects elements by their tag name.

let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length);

querySelector()

Returns the first element matching a CSS selector.

let firstParagraph = document.querySelector("p");
console.log(firstParagraph.textContent);

querySelectorAll()

Returns all elements matching a CSS selector.

let allParagraphs = document.querySelectorAll("p");
allParagraphs.forEach(p => console.log(p.textContent));

Modifying the DOM

Changing Content

You can modify the content of an element using textContent or innerHTML.

document.getElementById("title").textContent = "New Heading";
document.getElementById("content").innerHTML = "<b>Updated Content</b>";

Changing Attributes

You can modify attributes like src, href, alt, etc.

document.getElementById("myImage").src = "new-image.jpg";

Adding and Removing Elements

Create an element:

let newPara = document.createElement("p");
newPara.textContent = "This is a new paragraph.";
document.body.appendChild(newPara);

Remove an element

let oldPara = document.getElementById("removeMe");
oldPara.remove();

Event Handling in the DOM

JavaScript allows us to handle events such as clicks, keypresses, mouse movements, etc.

Adding an Event Listener

document.getElementById("btn").addEventListener("click", function() { 
   alert("Button Clicked!");
});

Removing an Event Listener

function sayHello() { 
   console.log("Hello!");
}
let btn = document.getElementById("btn");
btn.addEventListener("click", sayHello);
btn.removeEventListener("click", sayHello);

Event Object

The event object provides details about the event.

document.getElementById("inputField").addEventListener("keyup", function(event) {
   console.log("Key pressed: ", event.key);
});

Traversing the DOM

JavaScript provides properties to navigate through the DOM tree.

  • parentNode: Gets the parent element.
  • children: Gets all child elements.
  • firstChild / lastChild: Gets the first/last child.
  • nextSibling / previousSibling: Gets the next/previous sibling.

Example:

let parent = document.getElementById("myDiv").parentNode;
console.log(parent.tagName);

Advantages of Using the DOM with JavaScript

  • Interactivity: With the help of the JavaScript and DOM website can be interactive and dyanmic.
  • Real-time Updates: With the help of the JavaScript without refreshing we can update the content of the page, which makes the user experience faster.
  • User Input Handling: The DOM allows us to handle the user inputs in the forms due to which with the backend services there is the seamless communication.

JavaScript HTML DOM - FAQs

What is the HTML DOM?

The HTML DOM (Document Object Model) is a representation of an HTML document as a tree structure. It allows programming languages like JavaScript to access and manipulate the elements, attributes, and content of a webpage dynamically.

How does JavaScript interact with the HTML DOM?

JavaScript interacts with the HTML DOM by accessing elements via methods like getElementById, getElementsByClassName, and querySelector. It can modify the content, styles, and structure of HTML elements, as well as respond to user events (e.g., clicks or form submissions).

What is the purpose of DOM manipulation in JavaScript?

DOM manipulation in JavaScript allows developers to change the structure, content, and style of a webpage after it has been loaded. It helps create dynamic and interactive user interfaces by updating content without reloading the entire page.

Can JavaScript dynamically add or remove HTML elements?

Yes, JavaScript can create new HTML elements using methods like createElement() and append them to the page using appendChild(). It can also remove elements with removeChild() or parentNode.removeChild().

What are event listeners in the context of the DOM?

Event listeners are used in JavaScript to detect and respond to user actions, such as clicks, key presses, or mouse movements. These listeners can be added to DOM elements, and when the specified event occurs, the associated callback function is executed.


Next Article

Similar Reads

three90RightbarBannerImg