← Back to Chapters

JavaScript DOM Methods

? JavaScript DOM Methods

⚡ Quick Overview

DOM (Document Object Model) methods are built-in JavaScript functions that let you find, read, create, update, and remove HTML elements from a web page. Using these methods, you can change the content, attributes, and structure of the page dynamically without reloading it.

In short: DOM methods are how JavaScript “talks to” your HTML.

? Key Concepts

  • DOM Tree: The browser converts HTML into a tree of nodes (elements, text, attributes).
  • Selection Methods: Find elements in the DOM so you can work with them.
  • Content Methods: Change text or HTML inside elements.
  • Attribute Methods: Read or change attributes like id, class, src, etc.
  • Node Manipulation: Create, append, or remove elements from the DOM tree.

? When to Use DOM Methods

  • To update parts of a page (text, images, buttons) after a user action without reloading.
  • To build interactive UIs like modals, dropdowns, tabs, or to-do lists.
  • To generate content dynamically from data (lists, cards, tables, etc.).
  • To validate forms and show error messages near the related fields.

? Common DOM Methods

  • document.getElementById() – Selects an element by its ID.
  • document.getElementsByClassName() – Returns elements with the given class (HTMLCollection).
  • document.querySelector() – Selects the first element matching a CSS selector.
  • document.querySelectorAll() – Selects all elements matching a CSS selector (NodeList).
  • element.innerHTML – Gets or sets the HTML content inside an element.
  • element.textContent – Gets or sets the text content of an element.
  • element.setAttribute() / element.getAttribute() – Set or read element attributes.
  • element.appendChild() / element.removeChild() – Add or remove child elements.

? Syntax and Theory

? Selecting Elements

Use selection methods to grab references to elements you want to work with:

? View Selection Syntax
// Select an element by its id
const title = document.getElementById("title");

// Get all elements that have the class "card"
const cards = document.getElementsByClassName("card");

// Select the first button with class "primary"
const firstButton = document.querySelector("button.primary");

// Select all list items inside any <ul>
const allItems = document.querySelectorAll("ul li");

✏️ Changing Content and Attributes

Once you have an element, change its content or attributes:

? View Content and Attribute Syntax
// Replace only the text inside the element
title.textContent = "New Heading";

// Insert HTML markup inside the element
title.innerHTML = "New <strong>Heading</strong>";

// Add a custom data-* attribute to the element
title.setAttribute("data-level", "advanced");

// Read the value of that custom attribute
const level = title.getAttribute("data-level");

? Code Examples

? Example: Changing Content

This example selects elements using getElementById and querySelector, then updates their text and HTML content.

? View Code Example
// Get the element with id="title"
const heading = document.getElementById("title");
heading.textContent = "Hello, DOM Methods!";

// Select the first <p> element on the page
const para = document.querySelector("p");

// Replace its content with bold HTML text
para.innerHTML = "This paragraph has been updated using <strong>innerHTML</strong>.";

? Example: Creating and Appending Elements

Here we create a new <div> element, set its text, and append it to the end of the body.

? View Code Example
// Create a new <div> element in memory
const newDiv = document.createElement("div");

// Set the text that will appear inside it
newDiv.textContent = "I am a new div";

// Attach the new div at the end of the <body>
document.body.appendChild(newDiv);

? Interactive Example

Use the buttons below to see DOM methods in action. JavaScript will change the heading text and create new boxes dynamically.

? Live Demo Area

Original Demo Heading

Click the buttons to modify this content using DOM methods.

 
? View Demo HTML Markup
// Demo HTML structure used for the interactive example
<h4 id="demoTitle">Original Demo Heading</h4>
<p id="demoText">Click the buttons to modify this content using DOM methods.</p>
<button type="button" id="changeTextBtn">Change Text</button>
<button type="button" id="addBoxBtn">Add New Box</button>
<div id="boxContainer"></div>
? View Demo JavaScript
// Run this code only after the DOM is fully loaded
document.addEventListener("DOMContentLoaded", () => {
  // Grab references to all the elements we need
  const demoTitle = document.getElementById("demoTitle");
  const demoText = document.getElementById("demoText");
  const changeBtn = document.getElementById("changeTextBtn");
  const addBoxBtn = document.getElementById("addBoxBtn");
  const boxContainer = document.getElementById("boxContainer");

  // When 'Change Text' is clicked, update the heading and paragraph
  changeBtn.addEventListener("click", () => {
    demoTitle.textContent = "Updated with DOM Methods!";
    demoText.innerHTML =
      "This text was changed using <strong>textContent</strong> and " +
      "<strong>innerHTML</strong>.";
  });

  // When 'Add New Box' is clicked, create and append a new box <div>
  addBoxBtn.addEventListener("click", () => {
    const newBox = document.createElement("div");
    newBox.textContent = "New box " + (boxContainer.children.length + 1);
    newBox.setAttribute("data-created", "true");
    boxContainer.appendChild(newBox);
  });
});

? Live Output Explanation

When you click Change Text, JavaScript:

  • Selects the heading and paragraph using getElementById.
  • Updates the heading using textContent.
  • Updates the paragraph using innerHTML so it can include bold HTML tags.

When you click Add New Box, it:

  • Creates a new <div> using document.createElement().
  • Sets its text with textContent.
  • Adds a custom attribute using setAttribute().
  • Appends it to #boxContainer using appendChild().

? Tips and Best Practices

  • Use querySelector and querySelectorAll for flexible CSS-style selection.
  • Prefer textContent when inserting plain text to avoid HTML injection and XSS issues.
  • Only use innerHTML when you really need to insert HTML, and never with untrusted user input.
  • Cache DOM selections in variables if you access the same element multiple times.
  • Make sure your script runs after the DOM is loaded (e.g., using DOMContentLoaded).
  • Limit queries to specific containers instead of always querying the whole document for better performance.

? Try It Yourself

  • Select a button and change its text when it is clicked using textContent.
  • Create a list (<ul>) dynamically with createElement() and appendChild(), then append it to a container.
  • Use setAttribute() to add a custom attribute like data-role to an element and read it back with getAttribute().
  • Build a small “to-do” list where items are added and removed using DOM methods.