Javascript querySelector() and querySelectorAll() can be used to get DOM element based on given CSS selector. These works on document and element objects both. querySelector() returns first matched element whereas querySelectorAll() returns all matched elements. Here are some examples.
document – querySelector() example
<div id="id1"> Hello <div class="inner"> world </div> </div> <script type="text/javascript"> document.querySelector(".inner").style.backgroundColor="lightgreen"; </script>
DOM element – querySelector() example
<div class="inner">foo</div> <div id="id1"> Hello <div class="inner"> world </div> </div> <script type="text/javascript"> var dom1 = document.querySelector("#id1") dom1.querySelector(".inner").style.backgroundColor="lightgreen"; </script>
DOM element – querySelectorAll() example
<div class="inner">foo</div> <div id="id1"> Hello <div class="inner"> world </div> <script type="text/javascript"> var all = document.querySelectorAll(".inner"); for (var i = 0; i < all.length; i++) { all[i].style.backgroundColor = "lightgreen"; } </script>
Note that querySelector() and querySelectorAll() are not available on some very old browsers. Most modern browsers support these.