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 is the code.

document.querySelector(".container")

You can also check the output in the browser console.

This method can check whether an element with a specific class exists by using the following conditions.

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 as an object. Here is the code.

document.querySelectorAll(".container")

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

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

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top