Javascript DOM HTML Element querySelectorAll() Method

Introduction

Set the background color of the first element with class="example" inside of a <div> element:

Click the button to add a background color to the first element in DIV with class="example" (index 0).

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {//from  w w w . j a  v  a2s  .  c o m
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
  <h2 class="example">A heading with class="example" in div</h2>
  <p class="example">A paragraph with class="example" in div.</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 querySelectorAll() method returns a collection of an element's child elements that match a CSS selector(s) as a static NodeList object.

The NodeList object represents a collection of nodes.

The nodes can be accessed by index numbers. The index starts at 0.

element.querySelectorAll(CSS-selectors);

Parameter Values

Parameter Type Description
CSS-selectors String Required. Specifies one or more CSS selectors to match the element.

For multiple selectors, separate each selector with a comma.

The NodeList is a static collection, changes in the DOM has NO effect in the collection.

The querySelectorAll() method throws a SYNTAX_ERR exception if the specified selector(s) is invalid.




PreviousNext

Related