document querySelector examples

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.

queryselector-queryselectorall

document – querySelector() example

<div id="id1">
Hello
<div class="inner">
world
</div>
</div>
<script type="text/javascript">
  document.querySelector(".inner").style.backgroundColor="lightgreen";
</script>
refresh

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>
refresh

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>
refresh

Note that querySelector() and querySelectorAll() are not available on some very old browsers. Most modern browsers support these.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments