Element querySelector() Method - Use multiple selectors in querySelector() - Javascript DOM

Javascript examples for DOM:Element querySelector

Introduction

The following code will add a background color to the first <h2> element in <div>:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {/*from   w ww  . j ava 2  s  . c o  m*/
    border: 1px solid black;
}
</style>
</head>
<body>

<div id="myDIV">
  <h3>A h3 element in div</h3>
  <h2>A h2 element in div</h2>
</div>

<script>
var x = document.getElementById("myDIV");
x.querySelector("h2, h3").style.backgroundColor = "red";
</script>

</body>
</html>

if the <h3> is before <h2> in <div>. The <h3> element is the one that will get the red background color.

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {//from w  ww  .  j a va  2s  . c om
    border: 1px solid black;
}
</style>
</head>
<body>

<div id="myDIV">
  <h3>A h3 element in div</h3>
  <h2>A h2 element in div</h2>
</div>

<script>
var x = document.getElementById("myDIV");
x.querySelector("h2, h3").style.backgroundColor = "red";
</script>

</body>
</html>

Related Tutorials