Document Object Model (DOM) Selection is the process of selecting individual HTML objects using their tags, classes, and IDs.
There are five methods for selecting specific objects in the document.
To select a single element, we can use
Each method returns a reference to the first match of the selector.
This method selects a single element with an ID. Because there can only be one object with a specific ID on a page, this will only ever choose one element.
For example, we have an H2 with the id “Food”.
<h2 id="food">Favorite food</h2>
console.log(document.getElementById("food"));
// <h2 id="food">Favorite food</h2>
querySelector makes it easier to select things other than ID, such as classes and tags.
We need to specify what type of item we are selecting with the method, so an id would be selected with #id and a class with .class
console.log(document.querySelector('.container'));
console.log(document.querySelector('#todo'));
console.log(document.querySelector('h2'));
Note Because it’s a single element selector, even if there are more than 1 H2, it only selects the first H2.
To select all elements, we use multiple element selectors.
For example, we want to select all items in this list.
<ul class="items">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
querySelectorAll() selects all items that match, not just the first.
console.log(document.querySelectorAll(".item"));
/*
NodeList(3) [li.item, li.item, li.item]
0: li.item
1: li.item
2: li.item
length: 3
__proto__: NodeList
*/
It will return a NodeList, which is quite similar to an array. We can use Array methods on NodeList.
const items = document.querySelectorAll(".item");
items.forEach((item) => console.log(item));
/*
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
*/
This method selects all elements of a specific class.
It returns an HTMLCollection, which we can’t use array methods. We’ll have to convert it to an array manually.
console.log(document.querySelectorAll("item"));
/*
HTMLCollection(3) [li.item, li.item, li.item]
0: li.item
1: li.item
2: li.item
length: 3
__proto__: HTMLCollection
*/
This method selects all elements of a specific tag. It returns an HTMLCollection.
Examples of HTML tags are h1, p, li, div, etc.
console.log(document.getElementsByTagName('li'));