i'm trying to change each of my div's background color to black when my mouse enters the div using an eventlistener. it currently is only switching the first div to black but not any other div. why is my eventlistener only applying to the first 'contentDivs' div?
example:
this is my html code:
<body>
<div id="mainContainer"></div>
<script src="index.js"></script>
</body>
this is my javascript code:
for(x=0; x<64; x ) {
const contentDivs = document.createElement('div');
contentDivs.id = 'contentDivs';
document.getElementById('mainContainer').appendChild(contentDivs);
}
document.getElementById('contentDivs').addEventListener('mouseenter', () => {
document.getElementById('contentDivs').style.background = 'black';
})
this is what shows up when inspecting the elements in google chrome:
CodePudding user response:
If you want to select many elements you can use querySelectorAll
. If you want to select one please use querySelector
.
I've used minimal changes for your example. Ideally you should take advice of comments and change the identifying method to be class rather than id.
Lastly, I've added another effect using css alone, so you can compare how to make style changes using :hover class.
for (x = 0; x < 64; x ) {
const contentDivs = document.createElement('div');
contentDivs.id = 'contentDivs';
document.getElementById('mainContainer').appendChild(contentDivs);
}
document.querySelectorAll('#contentDivs').forEach(function(elem) {
elem.addEventListener('mouseenter', () => {
elem.style.background = 'black';
})
})
#contentDivs {
width: 20px;
height: 20px;
background: pink;
float: left;
margin: 10px;
transition: 500ms all;
}
#contentDivs:hover {
transform: scale(1.5);
}
<body>
<div id="mainContainer"></div>
</body>