DOM Basics in JavaScript

The Document Object Model (DOM) is a programming interface that allows JavaScript to access and modify the content, structure, and styles of an HTML webpage. It makes websites interactive by allowing developers to change text, update attributes, create elements, and respond to user actions.

Learning DOM basics is essential for JavaScript beginners because it explains how scripts interact with the HTML elements displayed in a browser.

What Is the DOM?

The DOM stands for Document Object Model. When a browser loads an HTML document, it creates a structured representation of the page that JavaScript can access.

The DOM represents HTML elements as objects organized in a tree-like structure. JavaScript can use these objects to read or change webpage content.

For example, consider this HTML:

<html>
  <body>
    <h1>Welcome to Web4Learners</h1>
    <p>Learn JavaScript step by step.</p>
  </body>
</html>

The browser represents the document as a hierarchy containing the HTML document, body, heading, and paragraph elements. JavaScript can access these elements and change their content.

Why Is the DOM Important?

The DOM allows JavaScript to interact with webpages after the browser has created their document structure.

You can use the DOM to:

  • Change text and HTML content.
  • Update element attributes.
  • Modify CSS styles.
  • Add or remove HTML elements.
  • Respond to clicks and other events.
  • Read values entered into form fields.

For example, you can change a heading when a user clicks a button. Learn how this works in our JavaScript in HTML tutorial.

Selecting HTML Elements with JavaScript

Before changing an element, JavaScript usually needs to select it from the DOM. Several methods are available for selecting HTML elements.

getElementById()

The getElementById() method selects an element by its ID.

<h1 id="title">Original Heading</h1>

<script>
  const heading = document.getElementById("title");
  heading.textContent = "Updated Heading";
</script>

The heading changes because JavaScript finds the element with id="title" and updates its text.

querySelector()

The querySelector() method selects the first element matching a CSS selector.

<p class="message">Welcome to JavaScript!</p>

<script>
  const paragraph = document.querySelector(".message");
  paragraph.textContent = "The DOM is working!";
</script>

The period in .message identifies a CSS class selector.

querySelectorAll()

The querySelectorAll() method selects all elements matching a CSS selector and returns a static NodeList.

<p class="item">HTML</p>
<p class="item">CSS</p>
<p class="item">JavaScript</p>

<script>
  const items = document.querySelectorAll(".item");

  items.forEach(function(item) {
    item.style.color = "blue";
  });
</script>

This example changes the text color of all three paragraphs.

Changing HTML Content with the DOM

JavaScript can update an element’s text using the textContent property.

<p id="message">This is the original message.</p>
<button id="changeButton">Change Message</button>

<script>
  const message = document.getElementById("message");
  const button = document.getElementById("changeButton");

  button.addEventListener("click", function() {
    message.textContent = "The message has been updated!";
  });
</script>

When the button is clicked, the paragraph displays the new message without reloading the page.

For more examples of click handling, read our button events tutorial.

Changing CSS Styles with the DOM

JavaScript can modify the inline styles of an HTML element through its style property.

<h2 id="heading">Learn Web Development</h2>
<button id="styleButton">Change Color</button>

<script>
  const heading = document.getElementById("heading");

  document.getElementById("styleButton").addEventListener("click", function() {
    heading.style.color = "blue";
    heading.style.fontSize = "30px";
  });
</script>

The button changes the heading’s text color and font size.

For larger projects, you can use CSS classes and JavaScript’s classList methods to keep styling rules separate from JavaScript logic.

Creating New HTML Elements

The DOM also allows you to create and insert new elements dynamically.

<ul id="courseList">
  <li>HTML</li>
</ul>

<button id="addButton">Add Course</button>

<script>
  const list = document.getElementById("courseList");

  document.getElementById("addButton").addEventListener("click", function() {
    const newItem = document.createElement("li");
    newItem.textContent = "JavaScript";
    list.appendChild(newItem);
  });
</script>

When the button is clicked, JavaScript creates a new list item and adds it to the existing list.

The createElement() method creates the element, while appendChild() inserts it into the DOM.

DOM Events in JavaScript

DOM events allow JavaScript to respond to user actions. Common examples include clicking buttons, typing into inputs, and submitting forms.

<input type="text" id="nameInput" placeholder="Enter your name">
<p id="output"></p>

<script>
  const input = document.getElementById("nameInput");
  const output = document.getElementById("output");

  input.addEventListener("input", function() {
    output.textContent = "Hello, " + input.value;
  });
</script>

As the user types, the paragraph updates with a greeting. Explore our HTML events tutorial to learn more about event handling.

Frequently Asked Questions

What does DOM stand for?

DOM stands for Document Object Model. It represents a document as objects that JavaScript can access and manipulate.

Is the DOM part of JavaScript?

The DOM is a web platform API provided by the browser, not part of the core JavaScript language itself. JavaScript can use the DOM API to interact with webpage elements.

What is the difference between HTML and the DOM?

HTML is the markup used to describe a webpage’s structure. The DOM is the browser-created object representation of the document that scripts can interact with.

Which method selects an element by ID?

The document.getElementById() method selects an element using its ID.

Final Thoughts

The DOM is a fundamental concept in JavaScript web development. It allows you to select HTML elements, update content, change styles, create elements, and respond to user actions. Start by practicing getElementById() and querySelector(), then explore event listeners and dynamic element creation to build interactive webpages.