Skip to main content

Command Palette

Search for a command to run...

JavaScript and the DOM – How They Work Together

Published
3 min readView as Markdown
JavaScript and the DOM – How They Work Together

The Document Object Model (DOM) is the backbone of dynamic web pages, enabling JavaScript to interact with HTML and CSS. Through the DOM, JavaScript can access, modify, and manipulate elements, making web pages interactive and responsive.

This article dives deep into how JavaScript interacts with the DOM, including element selection, content modification, event handling, and dynamic styling.

What is the DOM?

The DOM is a tree-like structure that represents an HTML document as nodes. These nodes allow JavaScript to interact with elements on the page dynamically.

DOM Structure Example

Consider this basic HTML structure:

<!DOCTYPE html>
<html>
<head>
  <title>DOM Example</title>
</head>
<body>
  <h1 id="heading">Hello, World!</h1>
  <p class="text">This is a paragraph.</p>
  <button id="changeText">Change Text</button>
</body>
</html>

The browser parses this HTML and converts it into a DOM tree, represented as:

Document
 ├── <html>
 │    ├── <head>
 │    │    ├── <title>DOM Example</title>
 │    ├── <body>
 │         ├── <h1 id="heading">Hello, World!</h1>
 │         ├── <p class="text">This is a paragraph.</p>
 │         ├── <button id="changeText">Change Text</button>

Now, let’s explore how JavaScript can manipulate this structure.

DOM Manipulation: Selecting and Modifying Elements

Selecting Elements in the DOM

JavaScript provides multiple ways to select elements:

1. Select by ID

heading = document.getElementById("heading");
console.log(heading.innerText);  // Output: Hello, World!
  • Returns a single element (if found).

  • Fastest method to find an element.

2. Select by Class Name

paragraphs = document.getElementsByClassName("text");
console.log(paragraphs[0].innerText);  // Output: This is a paragraph.
  • Returns an HTMLCollection (array-like, but not an array).

  • Use indexing paragraphs[0] to access individual elements.

3. Select by Tag Name

allParagraphs = document.getElementsByTagName("p");
console.log(allParagraphs.length);  // Output: Number of <p> tags
  • Returns all elements with the specified tag name.

4. Select with Query Selectors (Modern Approach)

firstParagraph = document.querySelector(".text");  // Selects first match
const allTextElements = document.querySelectorAll(".text"); // Selects all matches
  • querySelector() returns the first matching element.

  • querySelectorAll() returns all matching elements as a NodeList.

Modifying Content Dynamically with JavaScript

Changing Text and HTML

heading = document.getElementById("heading");
heading.innerText = "Welcome to JavaScript!";  // Changes the text
heading.innerHTML = "<span style='color: red;'>Updated Heading</span>";  // Injects HTML
  • .innerText changes only text content.

  • .innerHTML modifies the entire inner structure, allowing HTML injection.

Modifying Attributes

button = document.getElementById("changeText");
button.setAttribute("disabled", true); // Disables the button
console.log(button.getAttribute("id")); // Output: changeText
  • setAttribute(name, value) modifies an attribute.

  • getAttribute(name) retrieves an attribute.

Adding and Removing CSS Classes

paragraph = document.querySelector(".text");
paragraph.classList.add("highlight");  // Adds a class
paragraph.classList.remove("text");    // Removes a class
paragraph.classList.toggle("bold");    // Toggles a class on/off
  • .classList.add("className") adds a class.

  • .classList.remove("className") removes a class.

  • .classList.toggle("className") adds the class if missing, removes if present.

Changing Styles Dynamically

JavaScript can modify CSS properties directly:

heading = document.getElementById("heading");
heading.style.color = "blue";  // Changes text color
heading.style.fontSize = "24px";  // Increases font size
heading.style.backgroundColor = "yellow";  // Sets background color

🔹 Best Practice: Instead of modifying styles inline, prefer adding CSS classes.

.highlight {
  color: red;
  font-weight: bold;
}
heading.classList.add("highlight"); // Apply predefined CSS clas

Creating and Removing Elements in the DOM

Creating New Elements

newDiv = document.createElement("div"); // Create a new <div>
newDiv.innerText = "I am a dynamically created div!";
document.body.appendChild(newDiv); // Append to body
  • document.createElement("tagName") creates an element.

  • .appendChild(element) adds it to the page.

Removing Elements

paragraph = document.querySelector("p");
paragraph.remove(); // Removes the paragraph

Conclusion

Mastering the DOM (Document Object Model) is crucial for building dynamic and interactive web applications. By understanding how JavaScript interacts with the DOM, you can efficiently select, modify, create, and remove elements to enhance user experience.

Key Takeaways:

DOM is a tree-like structure representing HTML elements as nodes.
JavaScript allows dynamic content updates using innerText, innerHTML, and attribute manipulation.
Styles can be modified dynamically via .style properties or class manipulation.
Elements can be created and removed dynamically using document.createElement() and .remove().

More from this blog

Saleh's

41 posts