DEV Community

sterlingbarton
sterlingbarton

Posted on

The DOM Whisperer: How to Communicate Effectively with the Document Object Model

What even is the DOM?

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects — that way, programming languages can interact with the page. So, in short, the DOM is like a magical wizard wand that lets you control the elements on a web page and create new ones at will. It’s a powerful and fun way to make interactive web applications!

Selecting Elements

Before you can manipulate an element, you first need to select it from the DOM. Here are some methods for selecting elements:

  • document.getElementById(id) – returns a single element with the specified ID

  • document.getElementsByTagName(name) – returns a collection of elements with the specified tag name

  • document.getElementsByClassName(name) – returns a collection of elements with the specified class name

  • document.querySelector(selector) – returns the first element that matches the specified CSS selector

  • document.querySelectorAll(selector) – returns a collection of elements that match the specified CSS selector

If you’re feeling particularly ambitious, you can try selecting all the elements on the page at once. Just be warned, the DOM might not take kindly to your attempts at world domination.

Image description

Modifying Elements

Once you’ve selected an element, you can modify it in various ways. Here are some common methods for modifying elements:

  • element.innerHTML – gets or sets the HTML content of an element

  • element.innerText – gets or sets the text content of an element (ignores HTML)

  • element.setAttribute(name, value) – sets the value of an attribute for an element

  • element.style.property – sets the value of a CSS property for an element

  • element.classList.add(class) – adds a class to an element's list of classes

  • element.classList.remove(class) – removes a class from an element's list of classes

  • element.classList.toggle(class) – toggles a class on/off an element's list of classes

This is where you make your element dance, or even add some bling. We’re talking glitter, sparkles, and all things shiny.

 //makes the element spin//
element.style.animation = "spin 2s linear infinite";

// sets the background image to sparkles //
element.style.backgroundImage = "url('https://images.unsplash.com/photo-1519751138087-5bf79df62d5b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2370&q=80')";

Enter fullscreen mode Exit fullscreen mode

Creating and Appending Elements

You can also create new elements and append them to the DOM. Here are some methods for creating and appending elements:

  • document.createElement(tagName) – creates a new element with the specified tag name

  • element.appendChild(newElement) – appends a new element as a child of the specified element

  • element.insertBefore(newElement, existingElement) – inserts a new element before an existing element

Example

Here’s an example that demonstrates some of these concepts:

<!DOCTYPE html>
<html>
<head>
  <title>DOM Manipulation</title>
</head>
<body>
  <h1 id="myHeading">Hello World</h1>
  <button id="myButton">Click me</button>

  <script>
    // Get the heading element
    const heading = document.getElementById("myHeading");

    // Modify the heading element
    heading.textContent = "Hello JavaScript!";

    // Create a new paragraph element
    const paragraph = document.createElement("p");
    paragraph.innerText = "This is a new paragraph.";

    // Append the new paragraph to the body element
    document.body.appendChild(paragraph);

    // Add a click event listener to the button element
    const button = document.getElementById("myButton");
    button.addEventListener("click", function() {
      // Toggle a class on the heading element
      heading.classList.toggle("highlight");
    });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example, we select the h1 element with the ID myHeading, and modify its content using the textContent property. We then create a new p element using createElement and set its content using innerText. Finally, we append the new p element to the body element using appendChild.

We also select the button element with the ID myButton, and add a click event listener using addEventListener. When the button is clicked, we toggle a class on the h1

Conclusion

Don’t be afraid to get creative with your manipulation. Use animations, transitions, and other effects. DOM manipulation can be a lot of fun, but it’s important not to take things too seriously. If the DOM doesn’t cooperate with your plans, don’t get discouraged. Just try a different approach or take a break and come back to it later. When you’ve successfully manipulated the DOM, take a moment to celebrate your victory. Crack open a bottle of champagne, do a little victory dance, and bask in the glory of your DOM manipulation skills.

Image description

Check out my GitHub for more!

https://github.com/sterlingbarton

Top comments (0)