. Advertisement .
. Advertisement .
The querySelector() function in HTML is one of the best methods to return the first element to match a specified CSS selector. The following article will explain deeply about js queryselector and its functions.
What Is JS Queryselector?
JS queryselector or querySelector() is often employed to get the first element for a specific CSS selector. Yet, only the first element, which matches the chosen selector, is returned. For all matches, instead of using the querySelector(), you should use the querySelectorAll().
If there is no match found for your selector, you will get null result.
In this function, selectors are passed as a parameter. This string comes with at least one selector to match. It should be a valid selector string in CSS to avoid a possible SyntaxError exception.
In a standard CSS syntax, it is vital to use a backslash character to escape any characters not belonging to it. Be careful to use these backlash characters to write string literals correctly.
How Does The JS querySelector() Function Work?
The Universal Selector
One of the most common universal selectors is asterisk sign, which allows access to all document’s elements. If there is a literal string, you will have to escape the backslash twice.
Escape Special Characters
Escaping all special characters with a backlash is a must-do if you want to match against selectors or IDs. These selectors often fail to follow the standard CSS syntax.
<h1>Hello!</h1> <p>Welcome to Linux Hint!</p> <script> document.querySelector("*").style.color = 'red'; </script>
The Tag/Type Selector
You can pass the tag value to the method to search any element. For instance, you can get the HTML DOM’s <p> tag and change its color by using the following command:
<script> document.querySelector("p").style.color = 'red'; </script>
The # sign is one of the most widely used methods to select an element depending on its ID. It is worth noting that an ID should always be unique and no two elements present the same ID on a single HTML page.
Here is how to change the element’s color:
<script> document.querySelector("#example-id").style.color = 'red'; </script>
The dot selector for a class attribute selects an element depending on its class. While various elements share the same class, only the first element will be returned by the querySelector() function. Let’s see how to change the background color with this one:
<script> document.querySelector(".example-class").style.backgroundColor = 'red'; </script>
You can use the querySelector() for a combination of selectors as well. However, commas should be placed between two selectors to separate them.
Complex selectors are powerful, have a look at the following example:
const el = document.querySelector("div.user-panel.main input[name='login']");
The first input element is located with the name “login” inside a <div>. This one shows a user-panel main class in the document.
Leave a comment