JavaScript DOM Selectors

What is the DOM?

According to W3C, The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

The Selectors API

In the past jQuery allowed us to select elements from the DOM in a very easy way.

Since 2013 jQuery is no longer necessary thanks to the Selectors API .

The Selectors API provides methods that make it fast and easy to retrieve element nodes from the DOM. Here are a few examples:

Get Element by Id name

The selection is based on the Id name. This selector returns the first element that matches the specified CSS selector in the document.

1
2
3
4
5
// get element by id
const list = document.getElementById("list");

// change text color
list.style.color = '#DA4665';

Get Element by Class Name

The selection is based on the Class name. Returns a list of items that have a specific class name.

1
2
3
4
5
// get element by class name
const list = document.getElementsByClassName("list__item");

// change text color to the second item
list[1].style.color = '#DA4665';

Get Element by Tag Name

The selection is based on the Tag name. Returns a list of items that have a specific tag name.

1
2
3
4
5
// get element by tag name
const list = document.getElementsByTagName("li");

// change text color to the third item
list[2].style.color = '#DA4665';

QuerySelector

The method returns the first element that matches the specified CSS selector in the document. We can use all kinds of CSS selectors that we will use in a normal CSS file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// get element by Id
const list = document.querySelector("#list");

// get element by class name
const cat = document.querySelector(".list__item--cat");

// get element by tag name
const item = document.querySelector("li");

// styling
list.style.backgroundColor = '#6a7a7a';
cat.style.color = '#DA4665';

// apply to the first element that matches the specified CSS selector
item.style.color = '#aaafff';

QuerySelectorAll

This method returns all the elements that match the specified CSS selector in the document.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// get element by Id
const list = document.querySelectorAll("#list");

// get element by class name
const cat = document.querySelectorAll(".list__item--cat");

// get element by tag name
const item = document.querySelectorAll("li");

// apply to all the elements that matches the specified CSS selector
for (i = 0; i < item.length; ++i) {
  item[i].style.color = "#F24F82";
}

Thanks for reading, if you like the article be sure to subscribe down below to be the first to know when new articles are published. Also, we are always looking to improve if you got any constructive criticism let me know.

If you liked this article, consider becoming a patreon for $1, $5, $10 per month. Your support means so much!