Skip to content
Advertisement

display different comand and result from getElementsByClassName() Method

i just wanna ask how to change or display the different color with “getElementsByClassName() Method” in javascript,so here i want to change the bacground color blue from class “ex”,and color red form class “example”,but it doesnt work.

<!DOCTYPE html>
<html>
<head>
<style>
.example {
  border: 1px solid black;
  padding 8px;
}
</style>
</head>
<body>

<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>

<p>Change the background color of all elements with class="example":</p>

<div class="example">
A div with class="example"
</div>
<br>
<div class="ex">
A div with class="example"
</div>

<p class="example">
A p element with class="example".
</p>
<p class="ex">
A p element with class="example".
</p>

<p>A <span class="example">span</span> element with class="example".</p>

<script>
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
  collection[i].style.backgroundColor = "red";
}
const collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i++) {
  collection[i].style.backgroundColor = "blue";
}
</script>

</body>
</html>

Answer

your code works fine but you had two variables with the name collection rename one of them

<!DOCTYPE html>
<html>

<head>
  <style>
    .example {
      border: 1px solid black;
      padding 8px;
    }
  </style>
</head>

<body>

  <h1>The Document Object</h1>
  <h2>The getElementsByClassName() Method</h2>

  <p>Change the background color of all elements with class="example":</p>

  <div class="example">
    A div with class="example"
  </div>
  <br>
  <div class="ex">
    A div with class="example"
  </div>

  <p class="example">
    A p element with class="example".
  </p>
  <p class="ex">
    A p element with class="example".
  </p>

  <p>A <span class="example">span</span> element with class="example".</p>

  <script>
    const collection = document.getElementsByClassName("example");
    for (let i = 0; i < collection.length; i++) {
      collection[i].style.backgroundColor = "red";
    }
    const collection2 = document.getElementsByClassName("ex");
    for (let i = 0; i < collection2.length; i++) {
      collection2[i].style.backgroundColor = "blue";
    }
  </script>

</body>

</html>
Advertisement