querySelectorAll() Method in JavaScript
The querySelector()
method is used to return all the matching elements in the document. We can select elements by Tag Name, Class name, attribute name and etc.
Syntax
document.querySelectorAll(".cls"); //Returns all the matching elements with class name. document.querySelectorAll("p"); //Returns all the matching elements with class name.
The following example shows, how to select all <li>
elements using querySelectorAll()
method.
Example
<input type='button' value='Change Style' onclick='change_style()'> <ul> <li class='items'>List Item 1</li> <li class='items'>List Item 2</li> <li class='items'>List Item 3</li> <li class='items'>List Item 4</li> </ul> <script> function change_style(){ var a=document.querySelectorAll("li"); a.forEach(function(ele){ ele.style.color="green"; ele.style.fontWeight="bold"; }); } </script>Try it Yourself
Methods | Description |
---|---|
getElementById() | Used to return the matching element with given ID name. |
getElementsByClassName() | Used to return all matching elements with the given class name. |
getElementsByTagName() | Used to return all matching elements with the given tag name. |
getElementsByName() | Used to return all matching elements with the given name (name attribute). |
queryselector() | Used to return the first matching Element. |