Kind of a special case of this: Change CSS of the clicked element.
If I have some divs like this:
<div class="parent">
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
</div>
I know I can assign a function to each parent div like:
const parent = document.querySelectorAll('.parent');
if(parent.length){
for (let l of parent){
l.addEventListener('click', (e)=>{
l.classList.toggle('visible')
})
}
}
But how can I toggle the class .visible for the child div when the parent is clicked? Or alternatively add visibility:visible to the child div style.
Many thanks!
2
Answers
You can continue using
querySelector
, but this time start searching from your parent element, instead of from document.A bit of advice – it’s better to use buttons as interactive elements, since div doesn’t have any semantics and doesn’t show as an interactive element in accessibility tree. Also it can’t be activated with a keyboard. This makes your element inaccessible for some users. Using button will require only changing HTML and will make this much more usable.
You can use e.target for this then check if this target contains the .parent class then select its children with .child using e.target.querySelector to toggle the desired class.