0
2.0kviews
Explain in detail the role of querySelector() and querySelectorAll() methods in CSS with an example.
1 Answer
written 6.3 years ago by |
The querySelector() and querySelectorAll() methods accept CSS selector as parameters and return the matching element node in the document tree.
<!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>
<h1>
in the document.<h3>
element placed before the <h1>
element in the document, then <h3>
element is the one that will get the orange as background color.<!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>