JS Learning

DOM Manipulation

Lesson Progress0%

Topics

Selecting Elements

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Before you can change anything on a web page, you need to tell JavaScript which element you want to work with. It's like pointing at something and saying "I want to change THAT!"

The DOM (Document Object Model) is how JavaScript sees your HTML page - as a tree of elements that it can interact with.

Methods to find elements:

1. getElementById() - Find one element by its ID

This is the fastest way to find a single element with a unique ID.

HTML Example:
<h1 id="title">Hello World</h1>
JavaScript:
const titleElement = document.getElementById('title');
console.log(titleElement.textContent); // "Hello World"
2. getElementsByClassName() - Find all elements with a class
Returns a collection of all elements with the specified class name.
HTML Example:
<p class="highlight">First paragraph</p>
<p class="highlight">Second paragraph</p>
JavaScript:
const highlights = document.getElementsByClassName('highlight');
console.log(highlights.length); // 2
3. getElementsByTagName() - Find all elements of a type
Gets all elements of a specific HTML tag type.
JavaScript:
const allParagraphs = document.getElementsByTagName('p');
const allDivs = document.getElementsByTagName('div');
4. querySelector() - Find first match using CSS selectors
The modern way! Uses CSS selector syntax to find the FIRST matching element.
JavaScript:
document.querySelector('.header'); // First element with class "header"
document.querySelector('#main'); // Element with id "main"
document.querySelector('nav > ul'); // First ul inside nav
document.querySelector('[data-id="5"]'); // Element with data-id="5"
5. querySelectorAll() - Find all matches using CSS selectors
Like querySelector, but returns ALL matching elements.
JavaScript:
const allButtons = document.querySelectorAll('.button');
const allNavLinks = document.querySelectorAll('nav a');
const allChecked = document.querySelectorAll('input[type="checkbox"]:checked');

Which one to use?

  • For unique elements (one on the page):getElementById or querySelector
  • For groups of elements:querySelectorAll
  • querySelector/querySelectorAll are most flexible and modern!

Ready to practice? Try the exercise below to reinforce your learning!

Try it yourself

Practice different ways to select elements. Note: In this environment, DOM methods will be simulated.

Loading...
1 / 4