0
2.0kviews
Explain in detail the role of querySelector() and querySelectorAll() methods in CSS with an example.
1 Answer
0
24views

Role of querySelector() and querySelectorAll() Methods in CSS

The querySelector() and querySelectorAll() methods accept CSS selector as parameters and return the matching element node in the document tree.

Method querySelector()

  • The querySelector() method helps in querying the entire document or a specific element of the document. This method can use all CSS selectors as parameters.
  • The querySelector() method returns only the first element from multiple available elements which matches the specified selectors or if no element is available then returns null.
  • Example:
<!DOCTYPE html>
<html>
<body>
<h1>This is the h1 element</h1>
<p>This is the paragraph element</p>
<h3>This is the h3 element</h3>
<script>
document.querySelector("h1, p, h3").style.backgroundColor = "orange";
</script>
</body>
</html>
  • The above code will add a background color orange to the first element <h1> in the document.
  • Output:

Query Selector OP

  • If the <h3> element placed before the <h1> element in the document, then <h3> element is the one that will get the orange as background color.

Method querySelectorAll()

  • The querySelectorAll() method returns all the available elements in the form of a single static collection of elements known as staticNodeList.
  • The staticNodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
  • Any change in the document tree does not affect the staticNodeList.
  • It uses length property of the NodeList object to determine the number of elements that matches the specified selector.
  • Example:
<!DOCTYPE html>
<html>
<body>
<h1>This is the H1 element</h1>
<h3>This is the H3 element</h3>
<div style="border: 1px solid black;">This is DIV element</div>
<p>This is the paragraph element.</p>
<span> This is the span element</span> 
<p>Click the button to set the background color yellow for h3, div and span elements.</p>
<button onclick="coloryellow()">Click Me</button>
<script>
function coloryellow() {
    var x = document.querySelectorAll("h3, div, span");
    for (var i = 0; i < x.length; i++) {
        x[i].style.backgroundColor = "yellow";
    }
}
</script>
</body>
</html>
  • Output:

Query Selector All OP

  • In above example the background color is set for all elements selected by querySelectorAll() method in the document.
Please log in to add an answer.