-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
– Djpessoa
when I used querySelectorAll to work
– Djpessoa
@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.
– Djpessoa
If I understand correctly, I think this is what you want to do: https://jsfiddle.net/nd8jvto6/
– hkotsubo
@hkotsubo perfect! I will study your code that there is something beyond my knowledge! Thankful too!
– Djpessoa
@hkotsubo puts as an answer for me to close the topic and vote on your answer. Put only the js code
– Djpessoa
I answered, but I changed the code a little bit, I think it got a little better than jsfiddle
– hkotsubo