Javascript DOM HTML Element querySelector() Method by two tag names

Introduction

This example demonstrates how multiple selectors work.

Assume that you have two elements: a <h2> and a <h3> element.

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

View in separate window

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

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

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

</body>
</html>

if the <h3> element was placed before the <h2> element in <div>.

The <h3> element is the one that will get the red background color.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {//  w  w w  .  j a  v  a  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>



PreviousNext

Related