JavaScript program to update DOM

JavaScript is a powerful tool for dynamically updating the Document Object Model (DOM) of a web page. The Document Object Model (DOM) is an important part of web development that allows changing the structure, content, and style of a webpage. This article explains how to update the DOM using different methods and provides examples.

Understanding the DOM

DOM stands for Document Object Model. The DOM represents a webpage as a tree structure, where each element is a node. JavaScript allows developers to select, modify, and manipulate these elements in real time, making web pages dynamic and interactive.

DOM Tree Structure Document HTML HEAD BODY title h1 p button Each element is a node that can be selected, modified, or manipulated with JavaScript

Methods for Updating the DOM

JavaScript provides several methods to update the DOM dynamically:

Adding Elements

To add elements to the DOM, use createElement() to create a new element and appendChild() or insertBefore() to add it to the document.

Example: Adding a New Paragraph

<!DOCTYPE html>
<html>
<head>
    <title>Add Element Example</title>
</head>
<body>
    <h1>Welcome to My Webpage</h1>
    <button id="addParagraph">Add a Paragraph</button>
    <div id="content"></div>

    <script>
        function addNewParagraph() {
            // Create a new paragraph element
            let newParagraph = document.createElement('p');
            newParagraph.textContent = 'This is a dynamically added paragraph.';
            
            // Add some styling
            newParagraph.style.color = 'green';
            newParagraph.style.padding = '10px';
            newParagraph.style.border = '1px solid #ccc';
            newParagraph.style.marginTop = '10px';

            // Get the content container
            let contentDiv = document.getElementById('content');

            // Append the new paragraph
            contentDiv.appendChild(newParagraph);
        }

        // Add event listener to button
        document.getElementById('addParagraph').addEventListener('click', addNewParagraph);
    </script>
</body>
</html>

Removing Elements

Elements can be removed from the DOM using the remove() method or removeChild() method. The remove() method is modern and simpler.

Example: Removing Elements

<!DOCTYPE html>
<html>
<head>
    <title>Remove Element Example</title>
</head>
<body>
    <h1>Remove Elements from DOM</h1>
    <p id="removeMe" style="background: #ffebee; padding: 10px;">
        This paragraph will be removed when you click the button.
    </p>
    <button id="removeButton">Remove Paragraph</button>
    <button id="addBack">Add Paragraph Back</button>

    <script>
        function removeElement() {
            let elementToRemove = document.getElementById('removeMe');
            if (elementToRemove) {
                elementToRemove.remove();
                console.log('Element removed successfully');
            }
        }

        function addElementBack() {
            // Check if element already exists
            if (!document.getElementById('removeMe')) {
                let newParagraph = document.createElement('p');
                newParagraph.id = 'removeMe';
                newParagraph.textContent = 'This paragraph was added back to the DOM.';
                newParagraph.style.background = '#e8f5e8';
                newParagraph.style.padding = '10px';
                
                // Insert before the first button
                let firstButton = document.getElementById('removeButton');
                firstButton.parentNode.insertBefore(newParagraph, firstButton);
            }
        }

        document.getElementById('removeButton').addEventListener('click', removeElement);
        document.getElementById('addBack').addEventListener('click', addElementBack);
    </script>
</body>
</html>

Modifying Elements

You can modify existing DOM elements by changing their content, attributes, styles, or CSS classes. This is useful for creating interactive user interfaces.

Example: Modifying Element Properties

<!DOCTYPE html>
<html>
<head>
    <title>Modify Element Example</title>
    <style>
        .highlight {
            background-color: #ffeb3b;
            font-weight: bold;
            padding: 10px;
            border-radius: 5px;
        }
        .large-text {
            font-size: 20px;
        }
    </style>
</head>
<body>
    <h1>Modify DOM Elements</h1>
    <p id="modifyMe">Original text content</p>
    <button id="changeText">Change Text</button>
    <button id="changeStyle">Apply Styles</button>
    <button id="addClass">Add CSS Class</button>
    <button id="resetElement">Reset</button>

    <script>
        let element = document.getElementById('modifyMe');

        function changeText() {
            element.textContent = 'Text content has been modified!';
        }

        function changeStyle() {
            element.style.color = 'blue';
            element.style.fontSize = '18px';
            element.style.border = '2px solid red';
            element.style.padding = '10px';
        }

        function addClass() {
            element.classList.add('highlight', 'large-text');
        }

        function resetElement() {
            element.textContent = 'Original text content';
            element.style.cssText = ''; // Clear all inline styles
            element.className = ''; // Remove all classes
        }

        document.getElementById('changeText').addEventListener('click', changeText);
        document.getElementById('changeStyle').addEventListener('click', changeStyle);
        document.getElementById('addClass').addEventListener('click', addClass);
        document.getElementById('resetElement').addEventListener('click', resetElement);
    </script>
</body>
</html>

Common DOM Manipulation Methods

Method Purpose Example
createElement() Create new element document.createElement('div')
appendChild() Add element as last child parent.appendChild(child)
remove() Remove element element.remove()
textContent Change text content element.textContent = 'New text'
innerHTML Change HTML content element.innerHTML = '<b>Bold</b>'
classList.add() Add CSS class element.classList.add('active')

Best Practices

  • Use textContent over innerHTML when inserting plain text to prevent XSS attacks
  • Check if elements exist before manipulating them to avoid errors
  • Use CSS classes instead of inline styles for better maintainability
  • Cache DOM elements in variables if you'll use them multiple times
  • Use event delegation for dynamically added elements

Conclusion

JavaScript provides powerful methods for updating the DOM, enabling developers to create dynamic and interactive web pages. By mastering techniques for adding, removing, and modifying elements, you can build responsive user interfaces that react to user interactions in real-time.

Updated on: 2026-03-15T23:18:59+05:30

839 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements