I am attempting to change the backgroundColor of "gridElement" once "button" is clicked.
What was attempted, changing the way the elements are created to later include the event:
Also, attempting to make references to all gridElements:
How can I modify the code so that the eventListener will change all "gridElement" and not just the first?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title> Method 1 // appendChild() </title>
</head>
<body>
<div id="container">
<div id="gridContainer"></div>
</div>
<script>
const gridContainer = document.getElementById('gridContainer');
function createPixels(){
let pixels = 256;
for(let k=0;k<pixels;k++) {
const gridElement = document.createElement('div');
gridElement.classList.add('gridElement');
gridContainer.appendChild(gridElement);
window.allGridElements = gridElement;
}
}
createPixels();
const button = document.createElement('button');
button.classList.add('button');
button.textContent = 'button';
gridContainer.appendChild(button);
function changeBkg(){
window.allGridElements.style.backgroundColor = 'blue';
}
button.addEventListener('click', changeBkg);
</script>
</body>
</html>
The problem lies in your changeBkg function. To select all of the elements with the class of "gridElement", you want to use a for loop to find those elements and then change their styles. I added some basic css to the grid element so we can see the color change in action. Does that solve your issue?
.gridElement { width: 100px; height: 100px; background: red; display: inline-block; margin-right: 10px; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="CSS/main.css"> <title> Method 1 // appendChild() </title> </head> <body> <div id="container"> <div id="gridContainer"></div> </div> <script> const gridContainer = document.getElementById('gridContainer'); function createPixels(){ let pixels = 256; for(let k=0;k<pixels;k++) { const gridElement = document.createElement('div'); gridElement.classList.add('gridElement'); gridContainer.appendChild(gridElement); window.allGridElements = gridElement; } } createPixels(); const button = document.createElement('button'); button.classList.add('button'); button.textContent = 'button'; gridContainer.appendChild(button); function changeBkg(){ var items = document.getElementsByClassName('gridElement'); for (let i=0; i < items.length; i++) { items[i].style.backgroundColor = 'blue'; } } button.addEventListener('click', changeBkg); </script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.