We have many DOM methods to save html elements in JS variables. In this blog, I will be explaining how method "querySelector" works. And how we can select elements more specifically using this method.
How querySelector() works?
Consider a simple html code as below-
<!-- html -->
<html>
<body>
<input type="number">
<input type="number">
<input type="number">
</body>
</html>
If we need to store input element in JS variable, we use querySelector.
//JS code
var inputJS = document.querySelector("input");
console.log(inputJS)
//Output: <input type="number">
The above code in simple language means- querySelector() goes through the html document from top to bottom and selects 1st element with input tag, and returns it which gets saved in variable inputJS.
What is Selector?
What if we need to select 2nd input element instead of first, in such cases selectors are useful to call out specifically which element to select.
Whatever we write inside querySelector brackets is called as CSS string. It should have valid CSS syntax, if written incorrectly, it gives syntax error.
querySelector() method, searches for the element whose CSS selector matches with the CSS string specified in brackets. If no match is found it returns null.
We have some basic syntaxes-
- querySelector("TagName")
- querySelector(".ClassName")
- querySelector("#idName")
- querySelector("[Attribute]")
Lets check out one example:
<!-- html -->
<html>
<body>
<input class="inputNumber">
<input id="idName" >
<input type="number">
</body>
</html>
// JS code
var element1= document.querySelector("input");
var element2= document.querySelector(".inputNumber");
var element3= document.querySelector("#idName");
var element4= document.querySelector('[type="Number"]');
First querySelector searches for element with input tag in html document and returns
<input class="inputNumber">
, and it gets stored in variable element1.Second querySelector searches for element with class inputNumber ('.' represents class) in html document and returns
<input class="inputNumber">
, and it gets stored in variable element2.Third querySelector searches for element with id idName ('#' represents id) in html document and returns
<input id="idName">
, and it gets stored in variable element3.Fourth querySelector searches for element with attribute type and its value as Number ('[ ]' represents attribute) in html document and returns
<input type="number">
, and it gets stored in variable element4.
Multiple Selectors:
var element = document.querySelector(".inputNumber , #idName");
We can specify selectors comma separated. querySelector() searches for element who has either class inputNumber or id idName.
Negate Selectors:
var element = document.querySelector("input:not(.inputNumber)");
We can specify selectors inside brackets of :not() which we don't want to be selected. querySelector() searches for element who has input tag but that input element should not have class of inputNumber.
querySelectorAll():
var elementsArray = document.querySelectorAll("input");
querySelectorAll() searches for all the elements matching the CSS string and returns all those elements in an array.
Here it will return array of all the elements with tag input. We can store that array in variable.
This was just a basic understanding of selectors in JavaScript. Using this, you can build complex CSS strings. Here's a small quiz for you to check your understanding. Please write your answers in comments section.
<!-- html -->
<h1 class="mainHeader">Heading</h1>
<div class="main">
<h1>Heading Main</h1>
<p class="para">Paragraph</p>
<input type="text">
<p class="content">Content</p>
</div>
<div class="section">
<input type="text">
</div>
- Write CSS string if we want to select all elements with p tag having class "para" or "content"
- Write CSS string if we want to select an element with h1 tag and that element should not have "mainHeader" class
- Write CSS string for element with p tag having class "para" and parent class "main"
- Write CSS string if we want to select an element with input tag having attribute type="text" which does not have parent class "main"
- Find the output:
var array = document.querySelector("p") console.log(array[0]);