JavaScript DOM

1. What is the DOM?

The DOM (Document Object Model) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects.

Think of the DOM as a tree structure where every element (HTML tag) is a node. JavaScript can access and manipulate these nodes to create dynamic web pages.

2. Selecting Elements

To manipulate elements, you first need to select them. JavaScript provides several methods for this, ranging from selecting single elements to selecting collections.

Common Selectors

// 1. Select by ID (Returns a single element)
const title = document.getElementById("main-title");

// 2. Select by Class Name (Returns an HTMLCollection of elements)
const items = document.getElementsByClassName("list-item");

// 3. Select by Tag Name (Returns an HTMLCollection)
const paragraphs = document.getElementsByTagName("p");

// 4. querySelector (Returns the first element that matches the CSS selector)
const firstButton = document.querySelector("button");
const specificClass = document.querySelector(".container .box");

// 5. querySelectorAll (Returns a NodeList of all matching elements)
const allButtons = document.querySelectorAll("button");
        

3. Manipulating Content

Once you have selected an element, you can change its content using properties like innerHTML, textContent, and innerText.

// Assume HTML: <div id="content">Old Text</div>
const element = document.getElementById("content");

// 1. innerHTML - Parses HTML tags (Use carefully to avoid XSS)
element.innerHTML = "<strong>Hello World</strong>"; 

// 2. textContent - Sets plain text (ignores HTML tags, faster)
element.textContent = "Just plain text";

// 3. innerText - Similar to textContent but respects CSS styling (e.g., won't show hidden text)
element.innerText = "Visible text only";

// 4. value - Used specifically for form inputs
document.querySelector("input").value = "New Value";
        

4. Changing Styles & Attributes

You can dynamically change the CSS styles and HTML attributes of elements to update the look and feel of your page.

const box = document.createElement("div"); // Creating a dummy element for example

// Changing CSS styles
box.style.backgroundColor = "blue";
box.style.color = "white";
box.style.fontSize = "20px";
box.style.padding = "10px";

// Changing Attributes
const link = document.createElement("a");
link.setAttribute("href", "https://google.com");
link.setAttribute("target", "_blank");

console.log(link.getAttribute("href")); // "https://google.com"
link.removeAttribute("target"); // Removes the attribute
        
Output will appear here...

5. Creating & Removing Elements

You can create new HTML elements from scratch and add them to the DOM, or remove existing ones.

// 1. Create a new element
const newDiv = document.createElement("div");
newDiv.textContent = "I am a dynamically created div!";
newDiv.style.padding = "10px";
newDiv.style.border = "2px dashed #3b82f6";
newDiv.style.marginTop = "10px";

// 2. Append to a parent element (e.g., the output box below)
// document.body.appendChild(newDiv); // This would add it to the body

// 3. Remove an element
// newDiv.remove(); // Removes the element from the DOM

console.log("Element created:", newDiv.outerHTML);
        
Output will appear here...

6. Comparison: DOM Selectors

Selector Returns Type
getElementById Single Live
getElementsByClassName HTMLCollection (List) Live
querySelector Single Element Static
querySelectorAll NodeList (List) Static
Best Practice: Use querySelector and querySelectorAll for flexibility and consistency, as they accept any CSS selector (e.g., #id, .class, div > p). Use getElementById when performance is critical for selecting a single element.

Practice Questions

Test your understanding of JavaScript DOM Manipulation.

Easy

Q1: Select an element by its ID.

  • Assume there is an element with the ID main-heading.
  • Write the code to select this element.
  • Store it in a constant variable named heading.
Easy

Q2: Change the text content of an element.

  • Select an element with the ID message.
  • Change its text content to "Hello DOM!".
Medium

Q3: Change the style of multiple elements.

  • Select all <p> elements on the page.
  • Use a loop to iterate over them.
  • Change the text color of each paragraph to blue.
Medium

Q4: Create a new element and append it.

  • Create a new <li> element.
  • Set its text content to "New Item".
  • Append it to an existing <ul> with the ID list.
Hard

Q5: Remove an element from the DOM.

  • Select an element with the class box.
  • Write the code to remove it completely from the DOM.
  • Include a check to ensure the element exists before trying to remove it.

Answer

Code: