What are DOM selectors?

Types of DOM Selectors

There are 2 types of DOM selectors.

  1. Single element selector(Singular selector)
  2. Multiple elements selector(Plural selector)

1. Single element selector (Singular selector)

That means we can select only one node/element/object of the HTML within a document using a single element selector.

These are the single element selectors:

2. Multiple elements selector (Plural selector)

That means we can select multiple nodes/objects/elements of the HTML within a document.

These are the multiples element selector

Select by Id (getElementById)

Syntax:
- document.getElementById("ID")

Here I have selected an HTML element that has a unique id that is "text".Now the color of that element will be changed to red.

document.getElementById("text").style.color="red";

Select by query selector (querySelector)

Syntax:
- document.querySelector(".class")
- document.querySelector("#Id")
- document.querySelector("tag")

Now the element with the class name "text" will be green.

document.querySelector(".text").style.color="green";

Select by the class name (getElementsByClassName)

let items = document.getElementsByClassName("class");
console.log(items)  // return the list of items
items[3].textContent= "hello world"; // text changed
items[3].style.color = "red"; // color changed to red

We can not apply a style to the array but if we want to apply then we have to select a specific element using the "index" or using loops.Now all items inside the HTML collection will be green.

for(let a = 0;a<=items.length;a++){
    items[a].style.color = "green";
}

Select by tag name (getElementsByTagName)

let tagName = document.getElementsByTagName("li");
console.log(tagName)  // returns html collection
tagName[3].style.color = "red"; 

We can not apply a style to the array but if we want to apply then we have to select a specific element using the "index" or using loops.Now all items inside the HTML collection will be green.

for(let a = 0;a<=tagName.length;a++){
    tagName[a].style.color = "green";
}

Select by query selector all (querySelectorAll)

Syntax:

- document.querySelectorAll(".class");
- document.querySelectorAll("element");

let listItems = document.querySelectorAll(".class");
console.log(listItems)  // returns html collection
listItems[3].style.color = "red"; 

We can not apply a style to the array but if we want to apply then we have to select a specific element using the "index" or using loops. Now all items inside the HTML collection will be green.

for(let a = 0;a<=listItems.length;a++){
    listItems[a].style.color = "green";
}