Javascript DOM HTML Document querySelectorAll() Method

Introduction

Get all elements in the document with class="example":

var x = document.querySelectorAll(".example");

Click the button to add a background color all elements with class="example".

View in separate window

<!DOCTYPE html>
<html>
<body>

<h2 class="example">A heading with class="example"</h2>
<p class="example">A paragraph with class="example".</p>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {/*  w  w  w.  j av  a 2  s .co  m*/
  var x, i;
  x = document.querySelectorAll(".example");
  for (i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = "red";
  }
}
</script>

</body>
</html>

The querySelectorAll() method returns all elements that matches a specified CSS selector(s) as a NodeList object.

The NodeList object represents a collection of nodes.

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

document.querySelectorAll(CSS selector);

Parameter Values

Parameter
Type
Description
CSS selectors


String


Required.
Sets one or more CSS selectors to match the element.
For multiple selectors, separate each selector with a comma.

The querySelectorAll() method returns a NodeList object representing all elements in the document that matches the specified CSS selector(s).

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

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




PreviousNext

Related