Lesson 2: Selecting Elements

Learning Objectives

By the end of this lesson, learners will be able to:

  • Use JavaScript to select HTML elements in the DOM
  • Understand and apply four common DOM selection methods:
    • getElementById()
    • getElementsByClassName()
    • querySelector()
    • querySelectorAll()
  • Know when to use each method appropriately
  • Store selected elements in variables for further manipulation

Why Select Elements?

Before you can change or interact with an HTML element using JavaScript, you must first select it from the DOM.

Think of it like this:

The DOM is a big tree. To change something on a branch (like a paragraph), you need to first find that branch.


Method 1: getElementById(id)

Selects one element by its unique id attribute.

Syntax:

javascriptKopierenBearbeitendocument.getElementById("element-id");

Example:

HTML:

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

JavaScript:

let heading = document.getElementById("main-title");
console.log(heading.textContent); // "Welcome"

This method always returns a single element or null.


Method 2: getElementsByClassName(className)

Selects all elements with a given class name.

Syntax:

document.getElementsByClassName("some-class");

Example:

HTML:

<p class="highlight">Item 1</p>
<p class="highlight">Item 2</p>

JavaScript:

let items = document.getElementsByClassName("highlight");
console.log(items.length); // 2

Returns an HTMLCollection (like an array, but not quite). You can access items with indexes: items[0].


Method 3: querySelector(selector)

Selects the first element that matches a CSS-style selector.

Syntax:

document.querySelector("css-selector");

Example:

<p class="info">Paragraph 1</p>
<p class="info">Paragraph 2</p>
let firstInfo = document.querySelector(".info");
console.log(firstInfo.textContent); // "Paragraph 1"

Use this for flexible selection — works with IDs (#id), classes (.class), or tags (p, div, etc.)


Method 4: querySelectorAll(selector)

Selects all elements matching the CSS selector.

Syntax:

document.querySelectorAll("css-selector");

Example:

let paragraphs = document.querySelectorAll(".info");
paragraphs.forEach(p => console.log(p.textContent));

Returns a NodeList, which can be looped using forEach().


Comparison Table

MethodSelectsReturnsNotes
getElementById()One element (by ID)Element or nullFast and simple
getElementsByClassName()All elements with classHTMLCollectionNo forEach() support directly
querySelector()First matching elementElement or nullSupports all CSS selectors
querySelectorAll()All matching elementsNodeListUse forEach() to loop

Best Practices

  • IDs should be unique, so use getElementById() for single items
  • Use querySelector() for flexibility (e.g., nested elements like div > p)
  • For multiple elements, use querySelectorAll() and loop through the result