DEV Community

Rajat Gupta
Rajat Gupta

Posted on

querySelector method in Javascript

Does this sound familiar? made some logic in JS but unable to select the HTML element from which to take input for the logic to even execute or trying to read some text from an input div but unable to select the div or trying to select a button so that the user can click on it (in order to initiate some event) or trying to print some text in an text box when a button is clicked but unable to represent the text box in JS.

There is one solution for all your problems the almighty: querySelector.

Simply put, when making logic for a webpage, querySelector is the method that helps represent your HTML elements as Javascript variables.
You can select an HTML element based on either class or id. but, while doing so, the thing to keep in mind is that querySelector selects only the very first class or Id that it encounters in the HTML document.

Example: Let's see the below mentioned HTML page:

Alt Text

In the above page, we will type text in english in the class=txt-input and when we click the button having id=btn-translate, the text will be converted into banana language and shown in the div with the id=output.

Now in order to convert these HTML elements into JS variables, so that we can apply our logic, we use the below mentioned commands in .js file:

var txtInput = document.querySelector(".txt-input");
var outputDiv = document.querySelector("#output");
var btnTranslate = document.querySelector("#btn-translate");

But, what if you want to select 15 elements from HTML document in order to do some processing with them. Do, you have to apply querySelector individually for each element? No, you do not since in that case instead of using querySelector, we can use querySelectorAll(".className") and give it the class name and it will provide us with an array of the elements with the class name you provided. The index of these elements will be based on the fact that which element the querySelector encountered first while going through the HTML document from top to bottom.

Discussion (0)