JavaScript for Beginners: Mastering DOM Manipulation Step-by-Step

8.09K 0 0 0 0

📘 Chapter 2: Selecting and Accessing Elements in the DOM

🧩 Introduction: Getting Hands-On with the DOM

Now that you understand what the DOM is and how JavaScript interacts with it, the next step is learning how to select and access elements from your HTML structure. This is the foundation of everything you’ll do in dynamic web development — whether it’s changing content, adding styles, handling clicks, or creating new elements.

In this chapter, we’ll explore:

  • DOM selection methods (old and modern)
  • Targeting elements by ID, class, tag, and attributes
  • Differences between NodeList and HTMLCollection
  • When to use which method and why
  • Common pitfalls and how to debug them

🛠️ DOM Selection Methods Overview

There are five core methods to select elements in the DOM:

Method

Description

Return Type

getElementById()

Selects one element by ID

Single Element

getElementsByClassName()

All elements with a given class

HTMLCollection

getElementsByTagName()

All elements with a specific tag

HTMLCollection

querySelector()

First element that matches a CSS selector

Single Element

querySelectorAll()

All elements that match a CSS selector

NodeList


🔍 1. Selecting by ID — getElementById()

html

 

<h1 id="main-title">Welcome!</h1>

javascript

 

const title = document.getElementById('main-title');

title.textContent = 'Hello from JS!';

  • Fast and simple
  • Only works for unique IDs
  • Returns null if no element is found

🔎 2. Selecting by Class — getElementsByClassName()

html

 

<p class="intro">Intro 1</p>

<p class="intro">Intro 2</p>

javascript

 

const intros = document.getElementsByClassName('intro');

console.log(intros); // HTMLCollection

 

for (let i = 0; i < intros.length; i++) {

  intros[i].style.color = 'blue';

}

  • Returns an HTMLCollection
  • Live collection (updates if DOM changes)
  • Use a for loop or convert to array for forEach

🔎 3. Selecting by Tag — getElementsByTagName()

html

 

<ul>

  <li>Apple</li>

  <li>Banana</li>

</ul>

javascript

 

const listItems = document.getElementsByTagName('li');

 

for (let item of listItems) {

  item.style.listStyleType = 'square';

}

  • Works like class selector
  • Not limited to one parent
  • Ideal for batch formatting or cleanup

🧠 Key Differences: HTMLCollection vs NodeList

Feature

HTMLCollection

NodeList

Live updates

Yes

No

Loops

for, forEach (after conversion)

forEach available

Conversion to array

Array.from() or spread ([...collection])

Same


🧠 Example: Converting to Array

javascript

 

const items = document.getElementsByClassName('product');

const itemsArray = [...items]; // or Array.from(items)

 

itemsArray.forEach(item => item.classList.add('highlight'));


🌟 4. Selecting with CSS Selectors — querySelector()

html

 

<p class="description">Hello!</p>

javascript

 

const desc = document.querySelector('.description');

desc.textContent = 'Updated!';

  • Returns the first match only
  • Supports all CSS selectors: IDs (#), classes (.), tags, and attributes
  • Great for simple or specific selections

🌟 5. Selecting Multiple Elements — querySelectorAll()

html

 

<ul>

  <li class="link">Home</li>

  <li class="link">About</li>

  <li class="link">Contact</li>

</ul>

javascript

 

const links = document.querySelectorAll('.link');

links.forEach(link => link.style.fontWeight = 'bold');

  • Returns a static NodeList
  • Easy to use with forEach()
  • Best for modern JavaScript practices

📐 Advanced Selectors

🔹 Attribute Selector

html

 

<input type="text" name="email" />

javascript

 

document.querySelector('input[name="email"]');

🔹 nth-child

javascript

 

document.querySelector('ul li:nth-child(2)');

🔹 Descendant Selector

javascript

 

document.querySelector('.card .title');


🧪 Best Practices for Selecting Elements

  • Use querySelector / querySelectorAll as your default method
  • Use IDs only for unique elements (one per page)
  • Use class names for styling and JavaScript interaction
  • Always check if the element exists (if (element) {})
  • Use const for static elements and let if reassignment is expected

🧠 Real Example: DOM Selection in a Modal

html

 

<div class="modal hidden" id="infoModal">

  <p>This is a modal.</p>

  <button class="close-btn">Close</button>

</div>

javascript

 

const modal = document.getElementById('infoModal');

const closeBtn = document.querySelector('.close-btn');

 

closeBtn.addEventListener('click', () => {

  modal.classList.add('hidden');

});


Common Mistakes

Mistake

Fix

Using ID with querySelector() and forgetting #

Use '#elementId'

Using getElementById() on classes

Use getElementsByClassName() or querySelector()

Using forEach on HTMLCollection directly

Convert it to array first

DOM elements not found

Make sure script runs after DOM loads


🚦 Bonus: Wait for DOM to Load

Always make sure your code runs after the HTML has loaded:

javascript

 

document.addEventListener('DOMContentLoaded', () => {

  // Safe to select and manipulate elements here

});

OR place your <script> tag just before </body>


📋 Summary Table

Method

Returns

Supports

Use Case

getElementById()

Element

ID only

Fast single-element selection

getElementsByClassName()

HTMLCollection

Class

Grouped elements

getElementsByTagName()

HTMLCollection

Tags

Mass selection

querySelector()

Element

Full CSS selectors

Flexible, first match

querySelectorAll()

NodeList

Full CSS selectors

Multiple matches


📍 Summary: Key Takeaways

  • DOM selection is the foundation of web interactivity.
  • Use querySelector() and querySelectorAll() for modern flexibility.
  • Understand the structure and types of DOM collections (NodeList vs HTMLCollection).
  • Learn to access any element by ID, class, tag, or complex CSS selector.
  • Always ensure your scripts run after the DOM is ready.


Once you're confident with selecting elements, you're ready to move into modifying content and attributes — the next step in DOM mastery.

Back

FAQs


1. What is the DOM in JavaScript?

A: The DOM (Document Object Model) is a tree-like structure that represents your web page. JavaScript can access and modify this structure to change elements, styles, content, and more—dynamically and in real-time.

2. Is the DOM part of JavaScript?

A: Not exactly. The DOM is a Web API provided by the browser, but JavaScript interacts with it using built-in methods like getElementById, querySelector, and addEventListener.

3. How do I select an element using JavaScript?

Use DOM methods like:

document.getElementById('id')

document.querySelector('.class')

document.querySelector('tag')

4. What’s the difference between innerHTML and textContent?

  • textContent only sets or gets plain text.
  • innerHTML lets you read or change the HTML structure, including tags.

5. How do I change the style of an element using JavaScript?

element.style.color = "red";

element.style.backgroundColor = "yellow";

Or better, toggle CSS classes:

element.classList.add('active');

element.classList.remove('hidden');

6. How do I add a new element to the page dynamically?

const div = document.createElement('div');

div.textContent = "Hello!";

document.body.appendChild(div);

7. How do I remove elements from the DOM?

element.remove(); // Modern way

// OR

element.parentNode.removeChild(element); // Older method

8. How do I handle user clicks or input with JavaScript?

const button = document.querySelector('button');

button.addEventListener('click', function() {

  alert('Button clicked!');

});

9. What are some beginner DOM projects I can try?

  • To-do list
  • Click counter
  • Image gallery with buttons
  • Live character counter for input fields
  • Simple calculator
  • Dark/light mode toggle