The method querySelector is an essential JavaScript function utilized for locating elements within a document.
In this segment, we will explore the querySelector method, examining its application and reviewing an example to gain a practical understanding of the querySelector method.
Introducing JavaScript querySelector method
A method from the element interface that allows for searching and retrieving the first element present in the document is utilized here. It locates an element that corresponds to any of the given CSS selectors or a combination of selectors. In cases where no matching element exists, it will return null. The querySelector function is exclusive to the Document interface. This document interface outlines the standard methods and properties applicable to any HTML, XML, or similar types of documents.
How does the querySelector method perform the searching
It is understood that various search methods exist for locating elements. Nevertheless, the querySelector function employs a depth-first pre-order traversal technique to navigate the nodes within the document. This traversal begins with the initial element found in the document's markup and subsequently moves through the nodes in a sequential manner based on the hierarchy of child nodes.
Syntax
element = document.querySelector(selectors);
The querySelector function is a method associated with the document interface, which follows a specific syntax.
This function accepts a single argument, 'selectors', which is a string representing the DOM and can include one or multiple valid CSS selectors.
Return Type
It might yield 'null' in the event that no corresponding match exists. Conversely, if the initial element aligns with the given CSS selectors (if applicable), that element will be returned.
Nonetheless, in the absence of a valid CSS selector, a 'SyntaxError' exception will be raised.
Before we delve into an example of implementation, it is essential to familiarize ourselves with the different categories of CSS selectors. If you are not already acquainted with this topic, please refer to the CSS selector section of our CSS tutorial.
In this section, we will demonstrate a practical example where we will utilize a CSS selector to capture the value of its first element by employing the querySelector method.
Implementing querySelector Example
Here is an illustrative code snippet designed to help us comprehend the functionality of the querySelector method:
<html>
<head>
<meta charset="UTF-8">
<title> class="colors">Colors</title>
</head>
<body>
<h1> JavaScript Query Selector</h1>
<h1 class="myClass">Class 1</h1>
<p class="myClass"> Myclass</p>
<div id="firstid">
<p> It is the div p paragraph</p>
<p class="pclass"> div p class</p>
</div>
<p id="myid"> It is p id</p>
<div id="divid"> It is div id</div>
<script> <script>
//Element selector
var e=document.querySelector("p");
console.log(e);
</script>
</body>
</html>
The output of the above code is shown below:
Code Explanation
- The above code is a combination of html and JavaScript.
- We have implemented different CSS selectors in the code.
- In the JavaScript section, we have used a querySelector and invoked an element selector of CSS.
- So, the querySelector method now moves to the code for traversing it using the Depth-first pre-order method and returns the first element selector as it finds it.
In this manner, the querySelector function is invoked, and you can also experiment with utilizing the querySelector function for various other CSS selectors as well.
We will now explore and apply the same example utilizing alternative CSS selectors. Simply substitute the element selector code with the selector codes outlined below:
Few CSS Selectors
Class Selector
//Class selector
var e=document.querySelector(".myClass");
console.log(e);
To identify the first element of a class, it is necessary to utilize the (.) operator alongside the class name. The output will demonstrate that the querySelector method initiates its search from the beginning of the document and concludes upon locating the h1 class element. Consequently, the returned value is as specified in the example provided below:
ID Selector
//ID selector
var e=document.querySelector("#myid");
console.log(e);
Use (#) for using the ID selector of CSS.
The output will be as shown below:
Attribute Selector
//Attribute selector
var e=document.querySelector('[target]');
console.log (e);
The result produced by the code provided will be 'null' due to the absence of any attribute being utilized as illustrated below:
There exists a range of CSS selectors that can be utilized effectively if an individual possesses a thorough comprehension and insight into the different types of CSS selectors and their functionalities.
JavaScript querySelectorAll Method
The querySelector function in JavaScript is designed to select just the initial element that matches the specified criteria from the document. However, if the goal is to capture multiple values from CSS selectors, an alternative method from the Document interface is employed: the querySelectorAll method. This method is utilized to retrieve all elements that correspond to the specified CSS selector or a collection of CSS selectors.
Syntax
elementList = parentNode . querySelectorAll (selectors);
Within the syntax, there exists an argument known as selectors, which can accommodate one or multiple selectors that allow us to correspond with the values.
Return
In the event that the corresponding list or selector is located, it will yield the designated value associated with it. Conversely, if no match is detected, it will provide an empty nodeList as a result.
Additionally, if the defined CSS selectors include CSS pseudo-elements, the result will be an empty array.
Syntax Error
In the event of a syntax error, a syntax error exception will be raised indicating that the string of the specified selector is not valid.
Example
Here is the identical example we previously utilized to illustrate the querySelector method. Let us examine this example once more to grasp the distinctions between the two methods:
<html>
<head>
<meta charset="UTF-8">
<title> class="colors">Colors</title>
</head>
<body>
<h1> JavaScript Query Selector</h1>
<h1 class="myClass">Class 1</h1>
<p class="myClass"> Myclass</p>
<div id="firstid">
<p> It is the div p paragraph</p>
<p class="pclass"> div p class</p>
</div>
<p id="myid"> It is p id</p>
<div id="divid"> It is div id</div>
<script>
//Element selector
var e = document.querySelectorAll ("p");
console.log(e);
</script>
</body>
</html>
At this point, you can observe the distinction between the code presented in the initial example, where we utilized the querySelector method, resulting in the retrieval of just the first matching selector value. In contrast, when you examine the results from the subsequent example, you'll notice that it has provided all the matching values corresponding to the defined selectors or groups of selectors. The output generated by the code above is displayed below:
Code Explanation
- The above code is a combination of html and JavaScript.
- We have implemented different CSS selectors in the code.
- In the JavaScript section, we have used a querySelectorAll method and invoked an element selector of CSS.
- So, the querySelectorAll method now moves to the code for traversing it using the Depth-first pre-order method and returns all the matching element values that are specified as querySlectorAll method parameters.
Similarly, the querySelectorAll function can be utilized for different kinds of CSS selectors, returning all elements that correspond to the selectors provided as its argument. To apply this method, simply substitute the querySelector function with querySelectorAll for the desired selectors. This method will search for matches and will yield at least one matching element based on the specified criteria.