Home > OS >  display different comand and result from getElementsByClassName() Method
display different comand and result from getElementsByClassName() Method

Time:06-22

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 :</p>

<div >
A div with 
</div>
<br>
<div >
A div with 
</div>

<p >
A p element with .
</p>
<p >
A p element with .
</p>

<p>A <span >span</span> element with .</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>

CodePudding user response:

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 :</p>

  <div >
    A div with 
  </div>
  <br>
  <div >
    A div with 
  </div>

  <p >
    A p element with .
  </p>
  <p >
    A p element with .
  </p>

  <p>A <span >span</span> element with .</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>

CodePudding user response:

What does "doesn't work" mean? Is ex blue, and example uncolored? Are none colored?

Try checking the output in console (Developer tools - F12). I am certain you will receive an error using your snippet, as you redefine the collection variable twice. Use let instead of const if you plan on using a solution which changes a variable's value after assignment. Alternatively, define another variable for your second for-loop.

Here's your snippet corrected if you're still not sure:

let collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i  ) {
  collection[i].style.backgroundColor = "red";
}
collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i  ) {
  collection[i].style.backgroundColor = "blue";
}
  • Related