querySelector e querySelectorAll

Asked

Viewed 79 times

-1

I’m not sure how to solve a point of an exercise.

I have a JS function that expands a text within a div. In the first div it works normally, but in the following nothing happens.

how I make it work on all the Ivs. I would like to understand what I’m not seeing to make it work. The idea is that the two Divs have the same class name

<html>
<head>
    <title></title>
</head>
<body>
    <style>
        .conteudo h2 span{
            font-size: 13px;
            cursor: pointer;
        }

        .conteudo p{
            overflow: hidden;
            height: 10px;
            transition: 1s;
        }

        .mostrar{
            height: 200px !important;
        }
    </style>
    <div class="conteudo">
        <h2>Título do conteúdo <span>ver mais</span></h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing 
            elit. Pellentesque ac ligula vel sapien pellentesque 
            bibendum. Suspendisse posuere augue turpis, eget 
            luctus mauris molestie vel. Sed accumsan ex nibh, 
            vitae faucibus tortor luctus vitae. Sed aliquet, 
            diam sit amet porttitor suscipit, nisi velit venenatis 
            velit, eu accumsan orci ipsum commodo felis. In lectus 
            ipsum, fermentum non egestas sit amet, pellentesque 
            nec lacus. Donec erat lectus, gravida nec sagittis at, 
            sollicitudin vel turpis. Cras in pulvinar est.</p>
    </div>

    <div class="conteudo">
        <h2>Título do conteúdo <span>ver mais</span></h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing 
            elit. Pellentesque ac ligula vel sapien pellentesque 
            bibendum. Suspendisse posuere augue turpis, eget 
            luctus mauris molestie vel. Sed accumsan ex nibh, 
            vitae faucibus tortor luctus vitae. Sed aliquet, 
            diam sit amet porttitor suscipit, nisi velit venenatis 
            velit, eu accumsan orci ipsum commodo felis. In lectus 
            ipsum, fermentum non egestas sit amet, pellentesque 
            nec lacus. Donec erat lectus, gravida nec sagittis at, 
            sollicitudin vel turpis. Cras in pulvinar est.</p>
    </div>

    <script>

        var span = document.querySelector('.conteudo span');

         span.addEventListener('click', function(){
             alert('funcionou');

            var conteudo = document.querySelector('.conteudo p');

            if(conteudo.classList.contains('mostrar')){
                span.innerHTML = 'Ver mais!';
                conteudo.classList.remove('mostrar');
            }else{
                span.innerHTML = 'Ver menos!';
                conteudo.classList.add('mostrar');
            }
            
        });

    </script>
</body>
</html>
  • ignore Alert within the function

  • when I used querySelectorAll to work

  • @hkotsubo understood that querySelectorAll needs to iterate through a loop to know which div is being clicked. However bringing to this question here is not being simple for me.

  • 1

    If I understand correctly, I think this is what you want to do: https://jsfiddle.net/nd8jvto6/

  • @hkotsubo perfect! I will study your code that there is something beyond my knowledge! Thankful too!

  • @hkotsubo puts as an answer for me to close the topic and vote on your answer. Put only the js code

  • I answered, but I changed the code a little bit, I think it got a little better than jsfiddle

Show 2 more comments

1 answer

3


As stated above here, querySelectorAll returns a list of elements, then you should scroll through this list to add the events in each element. Now querySelector returns only the first element found.

But then it changes the way you do it a little bit. Inside the addEventListener you search for the paragraph that is in the same div of span clicked, so no use querySelector inside. That is, this line:

var conteudo = document.querySelector('.conteudo p');

The p who is in the first div. So you have to change the way you search a little bit.

I suggest you do the following:

  • search for all the div'the ones who have the class conteudo
  • add the click event on span that is inside the div
  • change the class of p that is inside the div

Would look like this:

// procura as div's que têm a classe "conteudo"
var divs = document.querySelectorAll('.conteudo');

// para cada div
divs.forEach(div => {
    // procura o span que está na div e adiciona o evento de clique
    var span = div.querySelector('span');
    span.addEventListener('click', function() {
        // procura o p que está dentro da div
        var conteudo = div.querySelector('p');
        if (conteudo.classList.contains('mostrar')) {
            span.innerHTML = 'Ver mais!';
            conteudo.classList.remove('mostrar');
        } else {
            span.innerHTML = 'Ver menos!';
            conteudo.classList.add('mostrar');
        }
    });
});
.conteudo h2 span{
    font-size: 13px;
    cursor: pointer;
}

.conteudo p{
    overflow: hidden;
    height: 10px;
    transition: 1s;
}

.mostrar{
    height: 200px !important;
}
<div class="conteudo">
    <h2>Título do conteúdo <span>ver mais</span></h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing 
        elit. Pellentesque ac ligula vel sapien pellentesque 
        bibendum. Suspendisse posuere augue turpis, eget 
        luctus mauris molestie vel. Sed accumsan ex nibh, 
        vitae faucibus tortor luctus vitae. Sed aliquet, 
        diam sit amet porttitor suscipit, nisi velit venenatis 
        velit, eu accumsan orci ipsum commodo felis. In lectus 
        ipsum, fermentum non egestas sit amet, pellentesque 
        nec lacus. Donec erat lectus, gravida nec sagittis at, 
        sollicitudin vel turpis. Cras in pulvinar est.</p>
</div>
<div class="conteudo">
    <h2>Título do conteúdo 2 <span>ver mais</span></h2>
    <p>Lorem ipsum 2 dolor sit amet, consectetur adipiscing 
        elit. Pellentesque ac ligula vel sapien pellentesque 
        bibendum. Suspendisse posuere augue turpis, eget 
        luctus mauris molestie vel. Sed accumsan ex nibh, 
        vitae faucibus tortor luctus vitae. Sed aliquet, 
        diam sit amet porttitor suscipit, nisi velit venenatis 
        velit, eu accumsan orci ipsum commodo felis. In lectus 
        ipsum, fermentum non egestas sit amet, pellentesque 
        nec lacus. Donec erat lectus, gravida nec sagittis at, 
        sollicitudin vel turpis. Cras in pulvinar est.</p>
</div>

Note that instead of searching from the document, i made:

var span = div.querySelector('span');

So he seeks only span that is inside the element pointed by div (instead of searching the entire document). This ensures that I will add the click event to the element inside that div. The same goes for the search for p, which is made from the div, so I guarantee I’ll change the class of the correct element.

  • 1

    I am impressed how didactic you were in that answer! If you are not a teacher you have everything to be! I am now trying to change the reason to actually absorb this from the querySelector and I am getting results. Thank you so much @hkotsubo

Browser other questions tagged

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