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);
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.
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
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.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.