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 Methods


What Are DOM Methods?

DOM methods are built-in JavaScript functions that allow you to interact with and manipulate web page elements. They let you select elements, modify content, change attributes, update styles, create new elements, remove existing elements, and even handle classes and events.

Think of DOM methods as tools in your toolkit. Just like a hammer or screwdriver helps build or fix things in the real world, DOM methods help you change and control your webpage dynamically. Without them, web pages would remain static, showing the same content to all users at all times.

Why DOM Methods Are Important

DOM methods are the foundation of interactive web pages. They make it possible to:

  • Update content dynamically: Change text, images, or other elements without refreshing the page.

  • Create new elements: Add new sections, lists, buttons, or forms on the fly.

  • Remove or replace elements: Remove outdated content or replace it with fresh information.

  • Modify attributes and styles: Change colors, sizes, and visibility of elements.

  • Add or remove CSS classes: Control element appearance and trigger animations dynamically.

By understanding DOM methods, you gain full control over your webpage’s structure and appearance, making it interactive and responsive to user actions.

Selecting Elements Using DOM Methods

Selecting elements is the first step in DOM manipulation. JavaScript provides several methods to access elements on a page.

getElementById()

Selects a single element by its id. It is fast and precise because IDs are unique.

let heading = document.getElementById("myHeading");
heading.textContent = "Heading Changed!";

getElementsByClassName()

Selects all elements with a specific class. Returns an HTMLCollection (similar to an array).

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

This is useful when you want to apply the same change to multiple elements.

getElementsByTagName()

Selects elements by their tag name. Returns an HTMLCollection.

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

querySelector() and querySelectorAll()

  • querySelector() selects the first element that matches a CSS selector.

let firstButton = document.querySelector(".btn");
firstButton.textContent = "Click Me!";
  • querySelectorAll() selects all elements matching a CSS selector and returns a NodeList, which can be looped with forEach.

let allButtons = document.querySelectorAll(".btn");
allButtons.forEach(btn => btn.style.backgroundColor = "yellow");

querySelectorAll is more flexible than getElementsByClassName because you can use any CSS selector, like IDs, classes, or element types.

Creating New Elements

DOM methods let you create new elements dynamically and add them to your page.

createElement()

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

createTextNode()

Sometimes you want to add only text to an element:

let textNode = document.createTextNode("Hello DOM!");
newDiv.appendChild(textNode);

This method is especially useful when building lists or paragraphs dynamically.

Inserting and Removing Elements

appendChild()

Adds a child element to a parent element.

let ul = document.querySelector("ul");
let li = document.createElement("li");
li.textContent = "New list item";
ul.appendChild(li);

insertBefore()

Inserts a new element before another element.

let firstLi = ul.firstElementChild;
let newLi = document.createElement("li");
newLi.textContent = "Inserted at first position";
ul.insertBefore(newLi, firstLi);

removeChild() and remove()

Removes an element from the DOM.

let lastLi = ul.lastElementChild;
ul.removeChild(lastLi);

// OR
lastLi.remove();

replaceChild()

Replaces an existing child element with a new element.

let newLi2 = document.createElement("li");
newLi2.textContent = "Replaced item";
ul.replaceChild(newLi2, ul.children[1]);

These methods allow full control over adding, removing, and rearranging elements dynamically.

Modifying Attributes and Styles

setAttribute() and getAttribute()

let img = document.querySelector("img");
img.setAttribute("src", "new-image.jpg");
console.log(img.getAttribute("src"));

removeAttribute()

img.removeAttribute("alt");

Changing Styles Directly

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

These methods let you control the appearance and behavior of elements in real-time.

Working With Classes

classList.add(), classList.remove(), classList.toggle()

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

These methods allow you to apply, remove, or toggle CSS classes dynamically, which is useful for animations and interactive effects.

Changing Content

innerHTML

Gets or sets HTML content inside an element.

let div = document.querySelector("#content");
div.innerHTML = "<p>New paragraph inside div</p>";

textContent

Gets or sets only text content (ignores HTML tags).

div.textContent = "Just plain text now";

innerText

Similar to textContent but respects CSS styles like display: none.

Practical Example

<div id="container">
    <h2 class="title">Old Title</h2>
    <p>Old paragraph</p>
</div>
// Change heading text
document.querySelector(".title").textContent = "New Title";

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

// Change container background
document.querySelector("#container").style.backgroundColor = "#f0f0f0";

This demonstrates how selecting, creating, and styling elements can work together for dynamic updates.

Summary of the Tutorial

DOM methods give you complete control over your webpage:

  • Select elements using IDs, classes, tags, or CSS selectors

  • Create and insert new elements dynamically

  • Remove or replace elements when needed

  • Update attributes, styles, and classes

  • Change content with innerHTML, textContent, or innerText

Mastering DOM methods is essential for building interactive and dynamic web pages. Once you are comfortable with these methods, you can move on to DOM events, navigation, and animations, creating fully responsive websites.


Practice Questions

  1. Select an element with the ID header and change its text to "DOM Methods Practice".

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

  3. Select all <p> elements using getElementsByTagName and append " - Updated" to their text content.

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

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

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

  7. Insert a new list item <li> before the first <li> in an existing <ul> using insertBefore.

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

  9. Select an image element and change its src attribute to a new URL using setAttribute.

  10. Select an element with ID container, add a new CSS class highlighted using classList.add(), then toggle it off after 3 seconds 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