Javascript DOM HTML Document 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 the document:

<h2>A h2 element</h2> 
<h3>A h3 element</h3> 
document.querySelector("h2, h3").style.backgroundColor = "red";

View in separate window

<!DOCTYPE html>
<html>
<body>

<h2>A h2 element</h2>
<h3>A h3 element</h3>

<script>
document.querySelector("h2, h3").style.backgroundColor = "red";
</script>//ww  w.j  a  v  a 2s .c o m

</body>
</html>

However, if the <h3> element was placed before the <h2> element in the document.

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

<h3>A h3 element</h3> <h2>A h2 element</h2> 
document.querySelector("h2, h3").style.backgroundColor = "red";

View in separate window

<!DOCTYPE html>
<html>
<body>

<h3>A h3 element</h3>
<h2>A h2 element</h2>

<script>
document.querySelector("h2, h3").style.backgroundColor = "red";
</script>// www .ja va  2s.  co  m

</body>
</html>



PreviousNext

Related