querySelector and querySelectorAll⁉

23-Dec, 2021

While learning how to use JS in HTML, I came across HTML DOM (Document Object Model). more specifically querySelector and querySelectorAll. Starting with document.querySelector.

What is Document.querySelector?

querySelector brings out the first instance of an object that has been called. Suppose you're calling an id from a doc.html file to a javascript, you'll use -

var object = doc.querySelector("#id-name")

or

var object = doc.querySelector(".class-name")

this is more-or-less useful when you want to work with only the first instance of an id that has been used multiple times. Though it is usually used to call an individual id(s) as each element in HTML is supposed to have a different id (usually the case). Next is-

What is Document.querySelectorAll?

querySelectorAll return all the instances (or a collection) of an object within the HTML file that have the same id or class. As it return a list of elements we can either index the element we want to work with or use a loop. The syntax of querySelectorAll is -

var object = doc.querySelectorAll("id")


For selecting based on index,


var object = doc.querySelectorAll("id")

object[i].style.color = "blue"


Tada

Hope this was even remotely helpful 😊.


Thank-you