An Introduction to querySelector() in JavaScript
querySelector()
querySelector() selects and returns the first element which matches the specified CSS selector.
document is an element interface which represents a webpage loaded in the browser and serves as an entry point into the webpage’s content.
document.querySelector() is an API via which we talk to browsers.
Eg:
document.querySelector(“selector”)
Through this we are telling the browser that we need that element: "selector"
The name 'querySelector' itself suggests that it asks for a particular selector and that selector is written like : ("selector").
It is a way by which we can connect the things in an html file to a javascript file.
Selector examples
- For textarea tag => document.querySelector("textarea")
- For element with class : "btn-primary" => document.querySelector(".btn-primary")
- For element with an id : input-btn => document.querySelector("#input-btn")
- For input Element with an attribute name: ‘translator’ => document.querySelector("input[name='translator']")
How does querySelector() work internally?
Suppose we have a element with id = "btn-click" in html file and var clickButton = document.querySelector("#btn-click") in javascript file, querySelector will go to the entire html page and will find whether there is an id = "btn-click". When it finds the match, it will return the entire element with the id, i.e ,
<button id ="btn-click">Click</button>
I hope it helps. Thank you for reading.