A Complete Guide - Web Designing JavaScript DOM Manipulation and Events

Last Updated: 03 Jul, 2025   
  YOU NEED ANY HELP? THEN SELECT ANY TEXT.

Web Designing: JavaScript DOM Manipulation and Events

Understanding the DOM The DOM (Document Object Model) represents the web page as a tree structure of objects, where each node is an object representing a part of the document. For example, elements like <div>, <span>, and tags like <h1>, along with text nodes, attributes, and other components, are treated as nodes in the DOM tree. Understanding how the DOM is structured helps in efficiently accessing and manipulating elements using JavaScript.

Accessing DOM Elements

There are several ways to access elements within the DOM:

  • By ID: document.getElementById('idName');
    • Retrieves the element that matches the specified ID.
  • By Tag Name: document.getElementsByTagName('tagName');
    • Returns a collection of all elements matching the specified tag name.
  • By Class Name: document.getElementsByClassName('className');
    • Returns a collection of all elements having the specified class name.
  • By Query Selector: document.querySelector('.className'); or document.querySelector('#idName');
    • Matches the first element based on a CSS selector.
  • By Query Selector All: document.querySelectorAll('.className');
    • Matches all elements based on the provided CSS selector.

Creating and Appending Elements To add dynamic elements to your web pages, JavaScript allows you to create new nodes in the DOM and insert them into the web page. Key methods include:

  • Creating Nodes
    • document.createElement(tagName);
      • Creates a new element node.
    • document.createTextNode(textString);
      • Creates a new text node.
  • Appending Nodes
    • parentNode.appendChild(childNode);
      • Adds a new child node at the end of the list of children of a parent node.
    • parentNode.insertBefore(newNode, referenceNode);
      • Inserts a new node before an existing child node.

Removing and Replacing Elements You can also remove or replace existing elements using these methods:

  • Removing Nodes
    • parentNode.removeChild(childNode);
      • Removes the specified child node from the parent node.
  • Replacing Nodes
    • parentNode.replaceChild(newNode, oldNode);
      • Replaces an existing child node with a new node in the DOM hierarchy.

Modifying Element Content and Attributes JavaScript DOM manipulation includes methods for changing the content and attributes of elements:

  • Changing Content
    • element.innerHTML = 'New HTML Content';
      • Sets the HTML content inside the specified element.
    • element.textContent = 'New Text Content';
      • Sets the text content inside the specified element.
  • Changing Attributes
    • element.setAttribute(attributeName, attributeValue);
      • Adds a specified attribute to an element or changes the value of an existing attribute.
    • element.getAttribute(attributeName);
      • Retrieves the specified attribute value from an element.
    • element.removeAttribute(attributeName);
      • Removes the specified attribute from an element.
  • Toggling Classes
    • element.classList.add(className);
      • Adds a given class to the list of classes on an element.
    • element.classList.remove(className);
      • Removes a specified class from an element.
    • element.classList.toggle(className);
      • Toggles between adding and removing a class from an element.

Manipulating CSS with JavaScript Styles can be updated dynamically via JavaScript in a number of ways:

  • Inline Styles
    • element.style.property = 'value';
      • Sets CSS properties directly on the style attribute.
  • CSS Classes
    • element.classList.add(className);
    • element.classList.remove(className);
    • element.classList.toggle(className);

Handling User Events Events are actions like user inputs (clicks, key presses) or browser actions (loading, closing) that trigger functions or scripts in response. Common event types include:

  • Mouse Events: onclick, onmouseover, onmouseout, etc.
  • Keyboard Events: onkeydown, onkeyup, onkeypress.
  • Form Events: onsubmit, onchange, onfocus, onblur.
  • Page Load Events: onload, beforeunload.

Event Types

  • Click Events: Triggered when the user clicks an element.
    element.addEventListener('click', function() {
        // Code to execute on click
    });
    
  • Hover Events: Triggered when the mouse pointer enters or leaves an element.
    element.addEventListener('mouseover', function() {
        // Code to execute on mouse over
    });
    element.addEventListener('mouseout', function() {
        // Code to execute on mouse out
    });
    

Event Propagation Events can travel up or down the DOM tree, affecting multiple nodes. There are two main phases of event propagation:

  • Capturing Phase: Event starts from the outermost element and moves inward towards the target element.
  • Bubbling Phase: Event starts from the target element and moves outward towards the outermost element.

Event Delegation

Event delegation leverages event bubbling to register a single event listener for similar events on a common ancestor rather than the individual nodes themselves. This technique saves memory and reduces overhead as it involves fewer event listeners.

document.body.addEventListener('click', function(event) {
    if (event.target && event.target.matches('.clickable')) {
        // Delegate action to the matched element
    }
});

Preventing Default Actions Sometimes it's necessary to stop the default behavior triggered by an event. For instance, stopping a form from submitting automatically. To do this, use the preventDefault() method.

form.addEventListener('submit', function(event) {
    event.preventDefault();
    // Additional code to handle form submission
});

Stopping Event Propagation To prevent events from bubbling up or capturing down the DOM tree, use the stopPropagation() method.

childElement.addEventListener('click', function(event) {
    event.stopPropagation();
    // Rest of the code
});

Important Properties and Methods Here's a comprehensive list of important properties and methods used in JavaScript DOM manipulation and event handling:

  • Properties
    • innerHTML: Sets or returns the HTML content of an element.
    • textContent: Sets or returns the textual content of an element.
    • style: Allows the setting or getting of inline CSS styles for an element.
    • classList: Provides an interface to manipulate the class attribute of an element.
    • attributes: Returns a live NamedNodeMap of all attributes on an element.
  • Methods
    • createElement(tagName): Creates a new element node.
    • createTextNode(textString): Creates a text node object.
    • appendChild(node): Adds a node as the last child of its parent node.
    • insertBefore(newNode, referenceNode): Inserts a new node before a specified child node.
    • removeChild(node): Removes a child node from its parent node.
    • replaceChild(newNode, oldNode): Replaces a child node with a new node.
    • setAttribute(name, value): Adds a new attribute or changes the value of an attribute.
    • getAttribute(name): Returns the value of a specified attribute.
    • removeAttribute(name): Removes a specified attribute.
    • addEventListener(eventType, callback): Attaches an event handler to an element.
    • removeEventListener(eventType, callback): Removes an event handler from an element.
    • preventDefault(): Prevents the default action for the event.
    • stopPropagation(): Stops further propagation of the current event.

Modern Techniques in DOM Manipulation While traditional DOM manipulation techniques are essential, modern frameworks and libraries like React and jQuery simplify these processes with their own sets of rules and abstractions. These tools offer improved performance, readability, and maintainability of code.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Web Designing JavaScript DOM Manipulation and Events

Example 1: Changing the Text of an HTML Element

Objective: Change the text of an HTML element when a button is clicked.

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Text Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #text-element {
            font-size: 24px;
            margin-top: 20px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <h1 id="text-element">Hello World!</h1>
    <button onclick="changeText()">Change Text</button>

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js)

function changeText() {
    // Select the HTML element using its ID
    const textElement = document.getElementById('text-element');
    
    // Change the text of the selected element
    textElement.textContent = 'Welcome to JavaScript!';
}

Explanation:

  1. In the HTML file, we have a heading (<h1>) with the ID text-element, which initially contains the text "Hello World!".
  2. We also have a button that triggers the changeText function when clicked.
  3. In the JavaScript file, document.getElementById('text-element') selects the <h1> tag.
  4. textContent property is used to change the text content of the selected element.

Example 2: Hiding and Showing an HTML Element

Objective: Hide and show an HTML element based on button clicks.

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hide and Show Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #toggle-box {
            width: 100px;
            height: 100px;
            background-color: green;
            margin-top: 20px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div id="toggle-box"></div>
    <button onclick="toggleVisibility()">Toggle Visibility</button>

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js)

function toggleVisibility() {
    // Select the div element using its ID
    const toggleBox = document.getElementById('toggle-box');
   
    // Check current display style; if it's block, set to none; otherwise, set to block
    if (toggleBox.style.display === 'none') {
        toggleBox.style.display = 'block';
    } else {
        toggleBox.style.display = 'none';
    }
}

Explanation:

  1. The HTML file contains a div with an ID toggle-box and a button that triggers the toggleVisibility function.
  2. Initially, the div is visible.
  3. When the button is clicked, the script checks if the display property of the div is 'none'.
  4. If it’s none (meaning the div is hidden), it changes the display property to block (to make it visible).
  5. If it’s not none, it sets the display property to none (hiding the element).

Example 3: Adding a List Item to an Existing HTML List

Objective: Add a new list item to an unordered list (<ul>) when a form is submitted.

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add List Item Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        ul {
            margin-top: 20px;
            padding-left: 0;
            list-style-type: none;
        }
        li {
            margin-bottom: 5px;
            padding: 5px 10px;
            background-color: #ddd;
            border-radius: 5px;
        }
        input {
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <h1>To-Do List</h1>
    <form id="todo-form">
        <input type="text" id="todo-input" placeholder="Enter a task">
        <button type="submit">Add Task</button>
    </form>
    <ul id="todo-list">
        <li>Learn HTML</li>
        <li>Learn CSS</li>
    </ul>

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js)

document.getElementById('todo-form').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent form submission from refreshing the page
    
    // Get the value from the input field
    const newItemValue = document.getElementById('todo-input').value;

    // Check if the input is not empty
    if (newItemValue) {
        // Create a new li element
        const newListItem = document.createElement('li');

        // Set the text content of the new li element
        newListItem.textContent = newItemValue;

        // Append the new li element to the ul
        document.getElementById('todo-list').appendChild(newListItem);

        // Clear the input field
        document.getElementById('todo-input').value = '';
    } else {
        alert('Please enter a task!');
    }
});

Explanation:

  1. The HTML file contains a input field and a submit button within a form (<form>), and an unordered list (<ul>) with existing list items.
  2. The script.js file adds an event listener to the form that triggers a function when the form is submitted.
  3. event.preventDefault() prevents the default behavior of the form submission which would refresh the page.
  4. It gets the value entered into the input field and creates a new list item (<li>) element.
  5. The text of the input field is added as text content of the new list item.
  6. The new list item is appended to the existing list (<ul>).
  7. After appending, the input field is cleared for the next entry.
  8. An alert prompts the user if they try to submit an empty form.

Example 4: Changing Background Color Using a Dropdown Menu

Objective: Change the background color of the webpage based on the selection from a dropdown menu.

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Background Color Changer</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        select {
            padding: 10px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <h1>Choose Your Background Color</h1>
    <select id="color-dropdown" onchange="changeBackgroundColor()">
        <option value="">Select a color...</option>
        <option value="blue">Blue</option>
        <option value="green">Green</option>
        <option value="yellow">Yellow</option>
        <option value="red">Red</option>
        <option value="purple">Purple</option>
    </select>

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js)

function changeBackgroundColor() {
    // Get the selected color
    const selectedColor = document.getElementById('color-dropdown').value;
   
    // Change the background color of the body
    document.body.style.backgroundColor = selectedColor;
}

Explanation:

  1. The HTML includes a dropdown select (<select>) populated with multiple color options.
  2. When the user selects a color, the onchange event listener triggers the changeBackgroundColor function.
  3. Inside this function, the currently selected color from the dropdown is retrieved using .value.
  4. The background color of the body element is changed to match the selected option.
 YOU NEED ANY HELP? THEN SELECT ANY TEXT.

Top 10 Interview Questions & Answers on Web Designing JavaScript DOM Manipulation and Events

1. What is the Document Object Model (DOM)?

Answer: The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree of objects: each node in the tree represents an aspect of the document, such as an element, attribute, or text. JavaScript provides methods and properties to interact with the DOM, allowing web pages to be dynamically updated.

2. How can you select an HTML element using JavaScript?

Answer: You can select HTML elements using various methods provided by the DOM API:

  • document.getElementById("idName"): Selects the element with the specified ID.
  • document.getElementsByClassName("className"): Selects all elements with the specified class name and returns a live HTMLCollection.
  • document.getElementsByTagName("tagName"): Selects all elements with the specified tag name and returns a live HTMLCollection.
  • document.querySelector("cssSelector"): Selects the first element that matches the specified CSS selector.
  • document.querySelectorAll("cssSelector"): Selects all elements that match the specified CSS selector and returns a static NodeList.

3. How do you modify the content of an HTML element using JavaScript?

Answer: You can modify the content of an HTML element using the textContent or innerHTML properties:

  • element.textContent = "New text": Sets the text content of the element, replacing all existing content.
  • element.innerHTML = "<span>New HTML</span>": Sets the HTML content of the element, allowing for the insertion of HTML tags and elements.

4. What is the difference between textContent and innerHTML?

Answer:

  • textContent gets or sets the text content of a node and its descendants, treating it as plain text. This is safer for setting content as it prevents HTML injection.
  • innerHTML gets or sets the HTML content of an element, interpreting the content as HTML. Use with caution to avoid XSS (Cross-Site Scripting) vulnerabilities.

5. How can you change the CSS style of an HTML element using JavaScript?

Answer: You can change the CSS style of an element using the style property:

element.style.color = "red";
element.style.backgroundColor = "yellow";

Alternatively, you can manipulate the class list to apply CSS rules defined in your stylesheet:

element.classList.add("active");
element.classList.remove("inactive");
element.classList.toggle("highlight");

6. What is an event in JavaScript and how do you handle it?

Answer: An event in JavaScript is an action that occurs in the browser, such as a user clicking a button, pressing a key, or the page finishing loading. Events can be handled using event listeners. You can add an event listener to an element using the addEventListener method:

element.addEventListener("click", function() {
    console.log("Button was clicked!");
});

The first argument is the name of the event, and the second argument is the function to be called when the event occurs.

7. What are the advantages of using event delegation?

Answer: Event delegation is the concept of adding an event listener to a parent element instead of each child element. The advantages of event delegation include:

  • Performance: Reduces the number of event listeners attached, improving performance, especially with many child elements.
  • Memory Efficiency: Reduces memory usage as fewer functions are attached.
  • Dynamic Content: Allows handling events for dynamically added elements without needing to attach listeners to them individually.

8. How do you remove an event listener in JavaScript?

Answer: To remove an event listener, you need a reference to the function that was added:

function handleClick() {
    console.log("Button was clicked!");
}

element.addEventListener("click", handleClick);
element.removeEventListener("click", handleClick);

Note that the function passed to removeEventListener must be the same as the one used with addEventListener.

9. What are some common JavaScript events used in web design?

Answer: Some common JavaScript events used in web design include:

  • click: Triggered when an element is clicked.
  • mouseover: Triggered when the mouse pointer is moved over an element.
  • mouseout: Triggered when the mouse pointer is moved out of an element.
  • keydown, keyup, keypress: Triggered when a key is pressed, released, or held down.
  • submit: Triggered when a form is submitted.
  • load: Triggered when an element (e.g., an image or the entire page) has finished loading.
  • resize: Triggered when the window is resized.
  • scroll: Triggered when the document (or an element) is scrolled.

10. How can you prevent the default action of an event in JavaScript?

Answer: To prevent the default action of an event (such as a link navigating to a new page or a form submitting), you can use the preventDefault method of the event object:

link.addEventListener("click", function(event) {
    event.preventDefault();
    console.log("Navigation was prevented!");
});

This method stops the event from performing its default behavior without stopping the event from continuing to propagate.

You May Like This Related .NET Topic

Login to post a comment.