Can you help me with my code bellow? Can’t seem to figure out how to loop through all the elements in array to change their background color from green to orange and back again on click. What I want it to do is change the background color of each specific div to orange on click and back to green again..and so on. What am I doing wrong?
//HTML
<!DOCTYPE html> <html lang="en-US"> <head> <title>Working With JavaScript Functions</title> <link href="index.css" rel="stylesheet" type="text/css" /> <script src="https://code.jquery.com/jquery-3.5.1.slim.js" integrity="sha256-DrT5NfxfbHvMHux31Lkhxg42LY6of8TaYyK50jnxRnM=" crossorigin="anonymous"></script> </head> <body> <div id='testA' style="background-color: green;" class="box"></div> <div id='testB' style="background-color: green;" class="box"></div> <div id='testC' style="background-color: green;" class="box"></div> <div id='testD' style="background-color: green;" class="box"></div> <div id='testE' style="background-color: green;" class="box"></div> <div id='testF' style="background-color: green;" class="box"></div> <script src="index.js"></script> </body> </html>
//CSS
.box { width: 75px; height: 75px; margin: 1rem; display: inline-block; }
//javascript
let greenBox = document.getElementsByClassName('box'); function boxClicked(event) { for (let i = 0; i <=greenBox.length; i++){ if (greenBox[i].style.backgroundColor === 'green') { greenBox[i].style.backgroundColor = 'orange'; } else { greenBox[i].style.backgroundColor = 'green'; } } } greenBox.addEventListener('click', boxClicked);
Advertisement
Answer
I believe your issue is that you are trying to add an event listener to a HTMLCollection
interface, which is invalid.
If what you want to do is to allow each .box
div’s background-colour to be changed on-click individually, you can setup a loop on page-load to add the event listener to each .box
div, then use the srcElement
property of the event
object to change the background colour.
Also, a minor suggestion unrelated to the question, consider renaming greenBox
to something more accurate like boxes
as the variable holds a collection of elements and they will not always be green. This is implemented in the solution below:
const boxes = document.getElementsByClassName('box'); for (let box of boxes) { box.addEventListener('click', boxClicked); } function boxClicked(event) { event.srcElement.style.backgroundColor = event.srcElement.style.backgroundColor === 'green' ? 'orange' : 'green'; }
Hope this helps.