Skip to Content
👆 We offer 1-on-1 classes as well check now
Web BasicsJavaScript DOMDOM Manipulation

DOM Manipulation

The Document Object Model (DOM) is a programming interface for web documents. It represents the page as a tree structure, allowing JavaScript to access and modify the content, structure, and style of HTML elements. This is how you make your webpages interactive!

What is the DOM?

The DOM is like a map of your webpage. It’s a structured representation of the HTML, CSS, and JavaScript that make up your website. Think of it as a tree where each branch is an HTML element (like a paragraph, a heading, or an image). JavaScript uses the DOM to find, change, add, or delete these elements, allowing for dynamic and interactive web experiences.

Basic Example: Changing Text

Let’s say you want to change the text of a paragraph on your webpage. Here’s how:

<!DOCTYPE html> <html> <head> <title>DOM Example</title> </head> <body> <p id="myParagraph">Hello, world!</p> <script> // Get the paragraph element by its ID const paragraph = document.getElementById("myParagraph"); // Change the text content paragraph.textContent = "Hello, DOM!"; </script> </body> </html>

Explanation:

  • document.getElementById("myParagraph"): This line finds the HTML element with the ID “myParagraph”.
  • paragraph.textContent = "Hello, DOM!";: This line changes the text content of the found paragraph element.

Practical Usage: Adding a New Element

Imagine you want to add a new list item to an unordered list when a button is clicked.

<!DOCTYPE html> <html> <head> <title>DOM Example 2</title> </head> <body> <ul id="myList"> <li>Item 1</li> <li>Item 2</li> </ul> <button id="addButton">Add Item</button> <script> const addButton = document.getElementById("addButton"); const myList = document.getElementById("myList"); addButton.addEventListener("click", function() { // Create a new list item element const listItem = document.createElement("li"); // Set the text content of the new list item listItem.textContent = "New Item"; // Append the new list item to the unordered list myList.appendChild(listItem); }); </script> </body> </html>

Explanation:

  • document.createElement("li"): Creates a new <li> (list item) element.
  • listItem.textContent = "New Item";: Sets the text of the new list item.
  • myList.appendChild(listItem);: Adds the new list item to the <ul> (unordered list).
  • addEventListener: It is used to listen to the click event on the button.

Key Takeaways

  • The DOM is a way to represent your webpage as a structured tree.
  • JavaScript uses the DOM to interact with HTML elements.
  • You can change text content, attributes, and styles using JavaScript.
  • You can add, remove, and modify elements to create dynamic web pages.
  • Using getElementById is a common way to select elements.
Last updated on