DEV Community

Cover image for Mastering DOM Manipulation in JavaScript
Dipak Ahirav
Dipak Ahirav

Posted on

Mastering DOM Manipulation in JavaScript

The Document Object Model (DOM) is an essential part of web development, allowing developers to dynamically change the structure, content, and style of web pages. In this post, we'll explore DOM manipulation in detail with examples, helping you master this crucial skill.

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

What is the DOM?

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of nodes, where each node corresponds to a part of the document (e.g., an element, attribute, or piece of text). With the DOM, JavaScript can interact with and modify the content and structure of a web page.

Selecting Elements

To manipulate the DOM, you first need to select the elements you want to work with. Here are some methods to do this:

  • document.getElementById(id): Selects an element by its ID.
  • document.getElementsByClassName(className): Selects all elements with the specified class.
  • document.getElementsByTagName(tagName): Selects all elements with the specified tag name.
  • document.querySelector(selector): Selects the first element that matches the CSS selector.
  • document.querySelectorAll(selector): Selects all elements that match the CSS selector.

Example: Basic DOM Manipulation

Here's a simple example demonstrating DOM manipulation:

<!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>
</head>
<body>
    <h1 id="header">Hello, World!</h1>
    <p class="paragraph">This is a paragraph.</p>
    <button id="changeTextBtn">Change Text</button>
    <button id="addElementBtn">Add Element</button>

    <script>
        // Selecting elements
        const header = document.getElementById('header');
        const paragraph = document.querySelector('.paragraph');
        const changeTextBtn = document.getElementById('changeTextBtn');
        const addElementBtn = document.getElementById('addElementBtn');

        // Changing text content
        changeTextBtn.addEventListener('click', () => {
            header.textContent = 'Hello, DOM!';
        });

        // Adding a new element
        addElementBtn.addEventListener('click', () => {
            const newParagraph = document.createElement('p');
            newParagraph.textContent = 'This is a new paragraph.';
            document.body.appendChild(newParagraph);
        });
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. HTML Structure: The HTML structure includes a header, a paragraph, and two buttons.
  2. Selecting Elements: Using document.getElementById and document.querySelector to select elements.
  3. Changing Text Content: Adding an event listener to the changeTextBtn button to change the text content of the header when clicked.
  4. Adding a New Element: Adding an event listener to the addElementBtn button to create a new paragraph element and append it to the body when clicked.

Modifying Styles

You can also modify the styles of elements using the style property.

Example

// Changing styles
header.style.color = 'blue';
header.style.fontSize = '2em';
Enter fullscreen mode Exit fullscreen mode

Removing Elements

You can remove elements using removeChild or remove.

Example

// Removing an element
document.body.removeChild(paragraph); // Using removeChild
header.remove(); // Using remove
Enter fullscreen mode Exit fullscreen mode

More Examples

Adding Classes

header.classList.add('highlight');
Enter fullscreen mode Exit fullscreen mode

Toggling Classes

header.classList.toggle('highlight');
Enter fullscreen mode Exit fullscreen mode

Setting Attributes

header.setAttribute('data-example', 'value');
Enter fullscreen mode Exit fullscreen mode

Getting Attributes

const attributeValue = header.getAttribute('data-example');
console.log(attributeValue); // Outputs: value
Enter fullscreen mode Exit fullscreen mode

Conclusion

DOM manipulation is a powerful feature of JavaScript that allows you to create dynamic and interactive web pages. By selecting elements and modifying their properties, content, and styles, you can significantly enhance the user experience. The examples provided should give you a solid foundation to start experimenting with DOM manipulation in your own projects.

Follow me for more tutorials and tips on web development. Feel free to leave comments or questions below!

Follow and Subscribe:

Top comments (6)

Collapse
 
jyoung4242 profile image
Justin Young

I'd add navigating up and down the DOM tree tips, with children and parent nodes and such... you cover selecting specific elements by id, query selections, tags, etc... but should cover parents siblings, first child, last child... etc.

Collapse
 
dipakahirav profile image
Dipak Ahirav • Edited

Thank you so much for your kind words and feedback! 🙏 I'm thrilled to hear that you found the post helpful. Your support means a lot to me. If you enjoyed this post, please consider subscribing to my YouTube channel devDive with Dipak for more content. Don’t forget to share it with your friends and help spread the word. Your support helps me to continue creating valuable content. Thanks again! 😊

Collapse
 
neurabot profile image
Neurabot • Edited

Cool. How do I test them ?

Collapse
 
dipakahirav profile image
Dipak Ahirav

Support me . please subscribe to my YouTube channel to support my channel and get more web development tutorials.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.