JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript DOM Elements


What Are DOM Elements?

DOM Elements are the individual HTML tags on a webpage represented as objects in the DOM tree. Every HTML tag, such as <div>, <p>, <h1>, <a>, or <img>, becomes a DOM element that JavaScript can interact with.

While the document object represents the entire page, DOM elements are the building blocks of the page you can manipulate individually. Each element has properties, methods, and attributes that allow you to read or modify content, styles, and behavior.

Why DOM Elements Are Important

Manipulating DOM elements is crucial for creating interactive webpages. Using DOM elements, you can:

  • Read or update content inside tags.

  • Change styles dynamically without refreshing the page.

  • Add, remove, or replace elements based on user actions.

  • Handle events like clicks, input changes, and hover effects.

  • Access element attributes such as src, alt, id, class, and more.

Every modern web application relies heavily on DOM element manipulation to provide a dynamic and responsive user experience.

Accessing DOM Elements

There are several ways to select DOM elements in JavaScript:

Using ID

let heading = document.getElementById("main-heading");
heading.textContent = "Heading Updated!";

IDs are unique, so this method returns a single element.

Using Class Name

let items = document.getElementsByClassName("item");
for (let i = 0; i < items.length; i++) {
    items[i].style.color = "blue";
}

This returns an HTMLCollection, allowing you to modify multiple elements at once.

Using Tag Name

let paragraphs = document.getElementsByTagName("p");
paragraphs[1].textContent = "Second paragraph updated";

This also returns an HTMLCollection of all elements with the specified tag.

Using CSS Selectors

let firstButton = document.querySelector(".btn");
firstButton.textContent = "Click Me!";
let allButtons = document.querySelectorAll(".btn");
allButtons.forEach(btn => btn.style.backgroundColor = "yellow");

querySelector selects the first matching element, while querySelectorAll selects all matching elements and returns a NodeList, which can be looped using forEach.

Modifying DOM Elements

Once an element is selected, you can modify its content, attributes, and styles.

Changing Text or HTML

let div = document.getElementById("content");
div.textContent = "This is updated text.";
div.innerHTML = "<p>This paragraph is added dynamically.</p>";
  • textContent updates only text.

  • innerHTML allows adding HTML structure inside the element.

Modifying Attributes

let image = document.querySelector("img");
image.setAttribute("src", "new-image.jpg");
image.setAttribute("alt", "Updated Image");
image.removeAttribute("title");

You can read, update, or remove attributes to control element behavior dynamically.

Modifying Styles

let heading = document.querySelector("h1");
heading.style.color = "red";
heading.style.fontSize = "30px";
heading.style.fontWeight = "bold";

Inline styles can be updated for instant visual changes.

Working With Classes

heading.classList.add("highlight");
heading.classList.remove("highlight");
heading.classList.toggle("highlight");

Classes let you apply pre-defined CSS rules dynamically, which is useful for themes, hover effects, and animations.

Creating and Adding DOM Elements

You can create new elements and insert them into the DOM.

let newDiv = document.createElement("div");
newDiv.textContent = "This is a new div.";
document.body.appendChild(newDiv);
  • createElement() creates a new element.

  • appendChild() adds it to a parent element.

You can also insert elements before existing ones:

let firstPara = document.querySelector("p");
let newPara = document.createElement("p");
newPara.textContent = "Inserted paragraph";
firstPara.parentNode.insertBefore(newPara, firstPara);

This allows precise control over element placement.

Removing or Replacing DOM Elements

Removing Elements

let lastPara = document.querySelector("p:last-child");
lastPara.remove();

Replacing Elements

let newHeading = document.createElement("h2");
newHeading.textContent = "New Heading";
let oldHeading = document.querySelector("h1");
oldHeading.parentNode.replaceChild(newHeading, oldHeading);

DOM manipulation makes it possible to update a page dynamically without reloads.

Traversing DOM Elements

You can navigate between elements using parent, child, and sibling relationships:

let firstLi = document.querySelector("li");
console.log(firstLi.parentNode);           // parent <ul>
console.log(firstLi.children);             // child elements if any
console.log(firstLi.nextElementSibling);   // next <li>
console.log(firstLi.previousElementSibling); // previous <li>

Traversal is important for manipulating elements relative to others.

Practical Example

<div id="container">
    <h1 id="main-heading">Old Heading</h1>
    <p>Old paragraph</p>
</div>
// Access elements
let heading = document.getElementById("main-heading");
heading.textContent = "Updated Heading";

// Create and append a new paragraph
let newPara = document.createElement("p");
newPara.textContent = "This paragraph is added dynamically.";
document.getElementById("container").appendChild(newPara);

// Change styles
document.getElementById("container").style.backgroundColor = "#f0f0f0";

This example shows how to access, modify, and add elements dynamically.

Summary of the Tutorial

DOM elements are individual HTML tags represented as objects in the DOM tree. By mastering DOM elements, you can:

  • Access elements using ID, class, tag name, or CSS selectors.

  • Modify content, attributes, and styles dynamically.

  • Create, add, remove, or replace elements on the page.

  • Traverse the DOM to manipulate elements relative to others.

Understanding DOM elements is essential for events, forms, animations, and interactive web development.


Practice Questions

  1. Select an element with the ID main-heading and change its text to "DOM Elements Practice".

  2. Select all elements with the class item and change their text color to red using a loop.

  3. Select all <p> elements on the page and append " - Updated" to their text content.

  4. Use querySelector to select the first element with the class title and change its background color to yellow.

  5. Use querySelectorAll to select all buttons on the page and change their font size to "20px".

  6. Create a new <div> element with some text and append it to the end of the <body>.

  7. Insert a new <p> element before the first paragraph on the page using insertBefore.

  8. Replace the second <li> in a <ul> with a new <li> containing "Replaced Item".

  9. Select an image element and update its src and alt attributes using setAttribute.

  10. Select an element with ID container, add a CSS class highlighted using classList.add(), then toggle it off using classList.toggle().


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top