Javascript Reference - HTML DOM querySelectorAll() Method








The querySelectorAll() method returns a collection of an element's child elements that match a specified CSS selector(s) as a NodeList object.

Browser Support

querySelectorAll Yes 9.0 Yes Yes Yes

Syntax

element.querySelectorAll(CSS selectors)

Parameter Values

Parameter Type Description
CSS selectors String Required. CSS selectors to match the element.




Return Value

Example

The following code shows how to set the background color of the first element with class="example" inside of a <div> element.


<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {<!--from   ww  w  .ja va  2 s . c om-->
    border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
  <h2 class="example">heading</h2>
  <p class="example">paragraph</p> 
</div>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    var x = document.getElementById("myDIV").querySelectorAll(".example");
    x[0].style.backgroundColor = "red";
}
</script>

</body>
</html>

The code above is rendered as follows: