I have a series of divs within the divs. HTML: I have 6 sets like this:
<div class="example" id="example1">
<div class="note">
<div class="backgr_color"></div>
<div class="note_text">
<h2>Text</h2>
<h3>Text</h3>
<div class="note_comment">
<p>Text</p>
</div>
<div class="note_bottom">
<p>text</p>
</div>
</div>
</div>
</div>
The "note" divs are squares, and the "backgr_color" divs are small dots inside the squares. I want to change the size and the color of the "backgr_color" dot when I mouseenter the corresponding "note" div.How can I do it using querySelectorAll instead of getElementById 6 times? I understand that I should iterate through both sets and find corresponding divs (note[2] = backgr_color[2]) but I cannot figure out how to do it? I don’t know JQuery yet so if there is a solution in JS, that would be great!
I understand how to iterate through notes_animation (notes) and affect the notes themselves but I don’t understand how to find the respective backgr_color dots?
let notes_animation = document.querySelectorAll(".note");
let backgr_color = document.querySelectorAll(".backgr_color");
for (i = 0; i < notes_animation.length; i++) {
notes_animation[i].addEventListener('mouseenter', function () {
this.style.backgroundColor = "red";
});
}
2
Answers
JS isn’t the right tool for this. CSS is a better approach as it’s designed to set the UI properties, and is also hardware accelerated so will perform better than JS’s event-based model.
You can achieve your goal by using the
:hover
pseudo-selector:If you really wanted to do this using JS then you can hook the event to all the
.note
elements in a loop, then usequerySelector()
to find the.backgr_color
element within the.note
that raised the event:It seems like you are very close. I would think you would want to add/remove a class to one of the html elements involved and handle the different styles via css. This is the approach I would suggest. If you want to remove the class on mouseleave though, you’ll have to add another event listener.