Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

HTML DOM Manipulation with JavaScript

What is DOM?

DOM is essentially a representation of a web page that your browser creates from HTML code. It's like a tree structure where each HTML element (like a paragraph, image, or heading) is a node in this tree. This model allows programming languages, primarily JavaScript, to interact with the web page. You can access and manipulate the page's content, structure, and styles through the DOM. It's like having a dynamic blueprint of the page that you can modify with code.

HTML DOM Manipulation with JavaScript

Manipulating the HTML Document Object Model (DOM) is a core functionality of JavaScript in web development. The DOM represents the page so that programs can change the document structure, style, and content. JavaScript can add, remove, and change HTML elements, attributes, and styles, as well as react to HTML events.

Selecting Elements

To manipulate a web page effectively, you first need to select the elements you want to work with. This is where selecting elements comes in. JavaScript provides various methods for this purpose:

  1. getElementById():

    • Selects an element based on its unique ID.
    • Example: document.getElementById("header") selects an element with the ID "header" (
  2. getElementsByClassName():

    • Selects all elements that have a specific class name.
    • If multiple elements share the same class, this method returns all of them.
  3. getElementsByTagName():

    • Selects elements based on their tag name (e.g., <p>, <div>).
  4. querySelector() and querySelectorAll():

    • These methods are more versatile.
    • querySelector() selects the first element that matches a specified CSS selector.
    • querySelectorAll() selects all elements that match the selector.
    • You can use CSS selectors to target elements by tag, class, ID, or even more complex combinations.

Understanding these selection methods is fundamental for effectively working with JavaScript to manipulate web pages.

Manipulating Elements

Once you've selected elements, you can use JavaScript to manipulate them in different ways:

  1. Changing content: You can update the text or HTML content inside an element. For instance:

    element.innerHTML = 'New content';
    

    This replaces the existing content with 'New content'.

  2. Modifying attributes: Attributes like src in an <img> tag or href in an <a> tag can be altered. For example:

    element.setAttribute('href', 'https://newurl.com');
    

    This changes the hyperlink of an anchor tag.

  3. Altering styles: You can adjust the CSS styles of elements. This is done by modifying the style property of an element. For example:

    element.style.color = 'red';
    

    This changes the text color of the selected element to red.

Understanding these concepts is crucial for effective JavaScript web development. By manipulating the DOM, you can create dynamic and interactive web pages that respond to user actions in real-time.

Examples of DOM Manipulation

  1. Changing Text Content:

    // Select the element with id "heading"
    var heading = document.getElementById("heading");
    // Change its text content
    heading.textContent = "Hello, World!";
    

    In this example, the content of the element with the id heading is changed to "Hello, World!".

  2. Updating HTML Content:

    // Select the element with id "paragraph"
    var paragraph = document.getElementById("paragraph");
    // Update its HTML content
    paragraph.innerHTML = "<em>New content</em>";
    

    In this example, the html content of the element with id paragraph is replaced with <em>New content</em>.

  3. Modifying Attributes:

    // Select an image element
    var image = document.querySelector("img");
    // Change its source attribute
    image.setAttribute("src", "newimage.jpg");
    

    In this example, we change the image src attribute value.

  4. Altering Styles:

    // Select an element with class "highlight"
    var highlightedElements = document.getElementsByClassName("highlight");
    // Change their background color
    for (var i = 0; i < highlightedElements.length; i++) {
        highlightedElements[i].style.backgroundColor = "yellow";
    }
    

    In this example, we change the background color of all elements with class highlight.

  5. Creating New Elements:

    // Create a new paragraph element
    var newParagraph = document.createElement("p");
    // Set its text content
    newParagraph.textContent = "This is a new paragraph.";
    // Append it to an existing element
    document.body.appendChild(newParagraph);
    

    This script creates a new paragraph element and adds it to the document body.

  6. Removing Elements:

    // Select the element to be removed
    var elementToRemove = document.getElementById("elementToRemove");
    // Remove it from the DOM
    elementToRemove.parentNode.removeChild(elementToRemove);
    

    In this example, we are targeting the element by ID and remove it from the it from the document OR HTML page.

  7. Event Handling:

    // Select the button element 
    var button = document.getElementById("myButton");
    // Add an event listener
    button.addEventListener("click", function() {
     alert("Button clicked!");
     });
    

    This example adds an event listener to a button, showing an alert when the button is clicked.

These examples demonstrate various ways JavaScript can manipulate the DOM to change content, attributes, styles, and even create or remove elements dynamically on a web page.