Contents: Click for quick access
How to Select DOM Elements with CSS Selectors
querySelector() Method
The technique Document querySelector() returns the first element within the document that matches the specified selector, or group of selectors which is useful in element searching. Null is returned if no matches have been found.
syntax
element = document.querySelector(selectors);
Example of querySelector to select a paragraph
<!DOCTYPE html>
<html>
<head>
<title>Example DOM querySelector() Method</title>
</head>
<body
<div id="gfg">
<p>I am going to writing a first paragraph</p>
<p>I am going to writing a second paragraph</p>
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("gfg");
x.querySelector("p").style.backgroundColor = "Green";
x.querySelector("p").style.color = "white";
}
</script>
</body>
</html>
querySelectorAll() Method
querySelectorAll() provides a static (not live) NodeList that represents a list of the document’s elements that match the specified set of selectors. A collection of nodes is represented by the NodeList object. Index numbers can be used to reach the nodes. The index begins at zero.
Example of querySelector to select all paragraphs with pink color
<!DOCTYPE html>
<html>
<head>
<title>Example DOM querySelector() Method</title>
</head>
<body
<div id="gfg">
<p>I am going to writing a first paragraph</p>
<p>I am going to writing a second paragraph</p>
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("gfg").querySelectorAll("p");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "pink";
x[i].style.color = "white";
}
}
</script>
</body>
</html>