.boxz {position: absolute; 499px; height: 300px; z-index: 500; background-color: blue;}
<div class="boxz" onclick="zfunction()"></div><br>
<div class="boxz" onclick="zfunction()"></div><br>
<div class="boxz" onclick="zfunction()"></div><br>
<div class="boxz" onclick="zfunction()"></div><br>
function zfunction(){
document.getElementsByClassName('boxz').style.bgColor = 'red';
//but only for the div clicked on
}
This returns a collection of matching elements. You would need to iterate over these to make it ‘work’. I’m surprised it did anything at all for you, since it produces an error - Uncaught TypeError: Cannot set properties of undefined …
Personally I would use an eventListener, but based on your code this should work.
HTML
<div class="box" onclick="changeBgColor(this)"></div>
<div class="box" onclick="changeBgColor(this)"></div>
<div class="box" onclick="changeBgColor(this)"></div>
<div class="box" onclick="changeBgColor(this)"></div>
CSS
.box {
width: 500px;
height: 300px;
background-color: blue;
margin-bottom: 1rem;
}
Javascript
function changeBgColor(elem) {
elem.style.backgroundColor = 'red';
}
You could do this if you have many boxes:
<!-- HTML -->
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
CSS
/* CSS */
.box {
width: 500px;
height: 300px;
background-color: blue;
margin-bottom: 1rem;
}
and an event listener:
document.addEventListener('DOMContentLoaded', () => {
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => {
box.addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
});
});
2 Likes
Great everyone, thanks!