How to capture another element within a loop to hide it

Asked

Viewed 17 times

-1

I’m having a difficulty, I want to hide a certain list when clicking a button, problem I have several buttons, I managed to solve assigning an id to the button and doing several checks of if, however I would like to know if there is the possibility of something more practical.

const btn = document.querySelectorAll('.show-block');

for(let item of btn){
    item.addEventListener('click', () => {
        let elemento = item.className;
        if(elemento.indexOf('ativo') !== -1){
            item.querySelector('ul');
            item.classList.add('show');
        }
        
    })
}
<div class="description-item">
            <h2>Modo de preparo</h2>
            <a class="show-block">Esconder</a>
                <ul>
                    {% for preparation in recipe.preparation %}
                        <li>{{preparation}}</li>
                    {% endfor %}
                </ul>
        </div>
        
        <div class="description-item">
            <h2>Modo de preparo</h2>
            <a class="show-block">Esconder</a>
                <ul>
                    {% for preparation in recipe.preparation %}
                        <li>{{preparation}}</li>
                    {% endfor %}
                </ul>
        </div>
        
        <div class="description-item">
            <h2>Modo de preparo</h2>
            <a class="show-block">Esconder</a>
                <ul>
                    {% for preparation in recipe.preparation %}
                        <li>{{preparation}}</li>
                    {% endfor %}
                </ul>
        </div>
        
        <div class="description-item">
            <h2>Modo de preparo</h2>
            <a class="show-block">Esconder</a>
                <ul>
                    {% for preparation in recipe.preparation %}
                        <li>{{preparation}}</li>
                    {% endfor %}
                </ul>
        </div>

When I try to capture UL and check by giving a console.log(ul) the value returned is null, someone would have some hint?

  • It would be better to put the rendered HTML in view of the template you have on the server

1 answer

0

Some mistakes to take into account:

  • item.querySelector('ul') will give empty because these elements are siblings (brothers, on the same level)
  • item.classList.add('show') will add the class to the item, which is the button, I assume you wanted to add to ul.

Forehead like this:

const btn = document.querySelectorAll('.show-block');

for (let item of btn) {
  const ul = item.closest('div').querySelector('ul');
  item.addEventListener('click', () => {
    if (elemento.indexOf('ativo') !== -1) {
      ul.classList.add('show');
    }

  })
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.