in Javascript

querySelector Method

What is querySelector method in javascript. The querySelector() method returns the first element that matches a specified CSS selector(s) in the document. In other words, it returns the first element that is a descendant of the element on which it is invoked, that matches the specified group of selectors.

javascript queryselector

The entire hierarchy of elements is considered when matching, including those outside the set of elements, including baseElement and its descendants. The resulting elements are then examined to see if they are descendants of baseElement. The first match of those remaining elements is returned by the querySelector() method.

Basic Syntax for querySelector

element = baseElement.querySelector(selectors);

baseElement we consider ‘document’, ‘querySelector’ is the javascript method and ‘selectors’ is the css selector in a document. So the javascript method will be used in the following way.

document.querySelector(".myDiv");

Here we are selecting the first element which has a class ‘myDiv’. In other words, the method returns the first element in the dom which has a class ‘myDiv’.

How to use multiple selectors?

The following example shows how multiple selectors works.

document.querySelector(".divLeft, .divRight").style.backgroundColor = "red";

The above code will select the elements with the two classes and apply background color ‘red’.

Now we will see what is querySelectorAll method.

querySelectorAll() method

The querySelectorAll() method returns a collection of an element’s child elements that match a specified CSS selector(s), as a static NodeList. The objectElementList is a non-live node list of element objects.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Syntax for querySelectorAll method

element.querySelectorAll(CSS selectors)

Example for querySelectorAll

Get all ‘p’ elements inside a ‘div’ element, and set the background color of the first ‘p’ element (index 0):

var a = document.getElementById("myDiv").querySelectorAll("p");  

a[0].style.backgroundColor = "red"; 

In object ‘a’ we are getting all the ‘p’ elements which are child elements of the div whose id is ‘myDiv’. Then we are applying background color to the first index element.

Written By:

Add a Comment

Your email address will not be published. Required fields are marked *