Manipulating DOM Elements with JavaScript

DOM (Document Object Model) manipulation refers to using JavaScript to dynamically interact with and modify the content, structure, or style of HTML elements on a webpage. The DOM represents the page so programs (such as JavaScript) can interact with it, changing elements, adding new content, or responding to user actions.

JavaScript provides many methods to manipulate these DOM elements, such as changing text, adding/removing elements, and modifying styles.

Key Concepts of DOM Manipulation

  1. Accessing DOM Elements

  2. Modifying DOM Elements

  3. Adding/Removing Elements

  4. Event Handling


1. Accessing DOM Elements

To manipulate an element, you first need to access it in the DOM using various selector methods.

Common DOM Selection Methods:

  • document.getElementById(): Selects an element by its id.

  • document.getElementsByClassName(): Selects elements by their class (returns a collection).

  • document.getElementsByTagName(): Selects elements by their tag name (returns a collection).

  • document.querySelector(): Selects the first matching element based on a CSS selector.

  • document.querySelectorAll(): Selects all matching elements based on a CSS selector (returns a NodeList).

Example:

<p id="myParagraph">This is a paragraph.</p>
<p class="myClass">This is another paragraph.</p>

<script>
  // Accessing elements
  let paraById = document.getElementById("myParagraph");
  let paraByClass = document.querySelector(".myClass");  // selects the first element with class "myClass"

  console.log(paraById);  // Logs: <p id="myParagraph">This is a paragraph.</p>
  console.log(paraByClass);  // Logs: <p class="myClass">This is another paragraph.</p>
</script>

2. Modifying DOM Elements

Once you have accessed an element, you can modify it. You can change:

  • Text Content: Using .innerHTML or .textContent.

  • Attributes: Using .setAttribute() or by directly modifying the attribute (e.g., src, href, etc.).

  • Styles: Using .style.

Example of Changing Text Content:

<p id="demo">Old Text</p>

<script>
  let paragraph = document.getElementById("demo");

  // Changing the text content of the paragraph
  paragraph.innerHTML = "New Text";  // Changes the content inside the <p> tag
</script>

In this example, the text "Old Text" inside the paragraph will be changed to "New Text".

Example of Changing Styles:

<p id="styleExample">Style me!</p>

<script>
  let styleExample = document.getElementById("styleExample");

  // Modifying the style of the element
  styleExample.style.color = "blue";  // Changes text color to blue
  styleExample.style.fontSize = "24px";  // Changes font size to 24px
</script>

In this example, we modify the color and font size of the paragraph using the .style property.


3. Adding/Removing DOM Elements

JavaScript allows you to dynamically add or remove elements from the DOM, creating a more interactive experience for users.

Example of Adding an Element:

<div id="container"></div>

<script>
  let container = document.getElementById("container");

  // Create a new paragraph element
  let newParagraph = document.createElement("p");
  newParagraph.textContent = "This is a new paragraph added dynamically.";

  // Append the new element to the container
  container.appendChild(newParagraph);
</script>
  • document.createElement(): Creates a new element (in this case, a <p> element).

  • appendChild(): Adds the new element as a child to the specified parent element (container).

Example of Removing an Element:

<p id="removeMe">Remove this paragraph.</p>

<script>
  let paragraph = document.getElementById("removeMe");

  // Remove the paragraph element
  paragraph.remove();
</script>
  • remove(): This method removes the selected element from the DOM.

4. Event Handling

Event handling allows your webpage to respond to user actions like clicks, keypresses, or mouse movements. When an event occurs, a JavaScript function (called an event handler) is triggered to execute certain actions.

Example of Adding a Click Event:

<button id="myButton">Click me</button>
<p id="outputText">I will change when the button is clicked.</p>

<script>
  let button = document.getElementById("myButton");
  let output = document.getElementById("outputText");

  // Add an event listener to the button
  button.addEventListener("click", function() {
    output.textContent = "The text has changed!";
  });
</script>

In this example:

  • addEventListener() is used to attach a click event to the button.

  • When the button is clicked, the text inside the paragraph will change.


Other Useful DOM Manipulation Methods:

  1. setAttribute(attributeName, value): Sets a new value to an attribute of an element.

     element.setAttribute("src", "image.jpg");  // Sets the "src" attribute of an image element
    
  2. getAttribute(attributeName): Retrieves the value of an attribute from an element.

     let srcValue = element.getAttribute("src");  // Gets the "src" attribute of an image element
    
  3. classList.add() / classList.remove(): Adds or removes classes from an element.

     element.classList.add("newClass");  // Adds the "newClass" to the element
     element.classList.remove("oldClass");  // Removes the "oldClass" from the element
    
  4. innerHTML vs textContent:

    • innerHTML allows you to set or get the HTML content of an element (including tags).

    • textContent only sets or gets the plain text, ignoring any HTML tags.

Example:

    <p id="demo"><strong>Bold Text</strong></p>
    <script>
      let paragraph = document.getElementById("demo");
      console.log(paragraph.innerHTML);  // Logs: <strong>Bold Text</strong>
      console.log(paragraph.textContent);  // Logs: Bold Text
    </script>

Full Example: Interactive DOM Manipulation

This example demonstrates how to use all the concepts we've discussed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Manipulation Example</title>
    <style>
        .highlight {
            background-color: yellow;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h2>DOM Manipulation Example</h2>
    <p id="myText">This is a paragraph.</p>
    <button id="changeText">Change Text</button>
    <button id="addParagraph">Add Paragraph</button>
    <button id="highlightText">Highlight Text</button>

    <div id="newContent"></div>

    <script>
        // Accessing elements
        let myText = document.getElementById("myText");
        let changeTextButton = document.getElementById("changeText");
        let addParagraphButton = document.getElementById("addParagraph");
        let highlightTextButton = document.getElementById("highlightText");
        let newContent = document.getElementById("newContent");

        // Changing text content
        changeTextButton.addEventListener("click", function() {
            myText.textContent = "The paragraph text has been changed!";
        });

        // Adding a new paragraph dynamically
        addParagraphButton.addEventListener("click", function() {
            let newPara = document.createElement("p");
            newPara.textContent = "This is a new dynamically added paragraph.";
            newContent.appendChild(newPara);
        });

        // Highlighting the text by adding a CSS class
        highlightTextButton.addEventListener("click", function() {
            myText.classList.add("highlight");
        });
    </script>
</body>
</html>

Summary of Key DOM Manipulation Techniques:

  • Accessing Elements: getElementById(), querySelector(), etc.

  • Modifying Content: innerHTML, textContent, style, etc.

  • Adding/Removing Elements: createElement(), appendChild(), remove().

  • Handling Events: addEventListener() to respond to user interactions.

Using these DOM manipulation techniques allows you to create interactive, dynamic webpages that can respond to user inputs and events in real-time.

Did you find this article valuable?

Support Sarthak by becoming a sponsor. Any amount is appreciated!