When to use javascript querySelector and querySelectorAll functions?

JavaScript provides two useful functions, document.querySelector() and document.querySelectorAll() to select and fetch data from the HTML nodes.

Use Case For document.querySelector():

If you need to fetch data from an element with a specific class, then you can use the document.querySelector() method. For example- you want to get the width of a div with a class name “container“. This function returns all the information of that div as an object. Here go the code.

document.querySelector(".container")

You can also check the output in the browser console.

This method can be used to check whether an element with a specific class exists by using the following condition.

if(typeof document.querySelector(".container") !== "undefined") {
  // write your code in here.
}

Use Case For document.querySelectorAll():

If you need to fetch data from multiple elements with a specific class, then you can use the document.querySelectorAll() method. For example- you want to get the width of all the divs with a class name “container“. This function returns all the information of multiple div’s as an object. Here go the code.

document.querySelectorAll(".container")

This method can select all the elements with a specific class by using the following condition.

 if(document.querySelectorAll(".container").length) {
    // write your code in here.
 }

Leave a Comment

Back To Top