Javascript DOM HTML Document querySelectorAll() Method by three tag names

Introduction

Set the background color of all <h2>, <div> and <span> elements in the document:

Click the button to set the background color of all h2, div and span elements.

View in separate window

<!DOCTYPE html>
<html>
<body>

<h1>A H1 element</h1>

<h2>A H2 element</h2>

<div>A DIV element</div>

<p>A p element.</p>

<p>A p element with a <span style="color:brown;">span</span> element inside.</p>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {// w  w  w  .j  av  a2  s  . c o m
  var x = document.querySelectorAll("h2, div, span");
  var i;
  for (i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = "red";
  }
}
</script>

</body>
</html>



PreviousNext

Related