skip to Main Content

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


  1. You can continue using querySelector, but this time start searching from your parent element, instead of from document.

    parent.addEventListener("click", (event) => {
      // `event.currentTarget` gives you element that event listener attached to.
      // it's not necessary, but I prefer to do this way.
      const child = event.currentTarget.querySelector(".child");
      // since `querySelector` can return `null`, it's never bad thing to check
      // using optional chaining is also a solution
      if (child === null) return;
      child.classList.toggle("visible");
    });
    

    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.

    Login or Signup to reply.
  2. 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.

    const parent = document.querySelectorAll('.parent')
    // console.log(parent)
    
    parent.forEach(div=>{
        div.addEventListener('click', (e) =>{
            let target = e.target
            // console.log(target)
            if(e.target.matches('.parent')){
                const children = e.target.querySelector('.child')
                children.classList.toggle('changeBackground')
            }
        })
    })
    .parent{
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100px;
        height:  100px;
        border: 2px solid black;
    }
    
    .child{
        display: flex;
        width: 50px;
        height: 50px;
        border: 1px solid red;
    }
    
    .child.changeBackground{
        background-color: yellow;
    }
    <div class="parent">
            <div class="child"></div>
        </div>
    
         <div class="parent">
            <div class="child"></div>
        </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search