querySelector() and querySelectorAll() Explained

Let's say we have three buttons with each one of them having a class of "btn". Now if we just want to access the first button or the first element then we use the querySelector() method of HTML DOM. So the querySelector() method returns the first element that matches a CSS selector, in the above case it will return the first button with the class of "btn"

<h1>Javascript is Fun</h1>
<button class="btn">Increase</button>
<button class="btn">Decrease</button>
<button class="btn">Reset</button>
const button=document.querySelector(".btn");
console.log(button);

console1.png Interesting right? Now tell me what if I want to select all the buttons with the class of "btn" then what should I do? .. just add 'all' to the above method which is querySelectorAll() This method returns all the elements with the class of "btn" in the form of static NodeList and if none of our elements match with the class of btn then it will return an empty NodeList.

const button=document.querySelectorAll(".btn");
console.log(button);

console2.png NodeList is very much same as HTML collection

NodeList is a collection of document nodes which could be element nodes, attribute nodes , or text nodes taken from HTML documents. A NodeList may look like an array but it's not ,yes we can access the items by their index number but we cannot use the methods like push(),pop(),shift(),unshift() on a NodeList.

To iterate over the NodeList items we can use forEach() loop.

Below is an example ,how we can access any node in the NodeList

const thirdNode=document.querySelectorAll(".btn")[2];
console.log(thirdNode);

console3.png

That's it from this one .

HAPPY CODING!