JavaScript DOM Methods
DOM methods are ways to find elements on the page. querySelector finds the first element matching a selector, and other methods cover the rest of the cases.
Find by tag
The selector h1 matches the heading element. Reading its text shows the element it found.
const heading = document.querySelector("h1");
console.log(heading.textContent);Find by id
The #demo selector finds the element with that id. It is the same paragraph getElementById finds.
const demo = document.querySelector("#demo");
demo.textContent = "Found by id";
console.log(demo.textContent);Find all matches
querySelectorAll collects every match into a list. The practice page holds one paragraph, so the length is 1.
const paragraphs = document.querySelectorAll("p");
console.log(paragraphs.length);Example
const heading = document.querySelector("h1");
console.log(heading.textContent);
const paragraphs = document.querySelectorAll("p");
console.log(paragraphs.length);
const missing = document.querySelector("span");
console.log(missing);Key points
- A selector is a pattern that describes which element to find.
- In a selector, # means an id and . means a class, as in the CSS course.
- querySelector returns the first element that matches the selector.
- querySelectorAll returns every element that matches the selector.
- querySelector returns null when no element matches.
- getElementsByTagName finds elements by their tag name instead.
In this example, querySelector finds the heading and reads its text. querySelectorAll counts the one paragraph on the page. The last search finds no span element, so it returns null.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does querySelector return when no element matches the selector?