Change properties of a single element that repeats over and over again on my page

Asked

Viewed 41 times

3

I have a div with the same classes repeating several times on my page (only changes the content) and I want to select only the element that was clicked.

Example of the code I’m using:

jQuery(function() {
    jQuery('p').hide();
    jQuery('.readmore').click(function(){
      if(jQuery('p').hasClass('mostrando')){
        jQuery('p').removeClass('mostrando');
        jQuery('p').fadeOut('fast');
      } else {
        jQuery('p').addClass('mostrando');
        jQuery('p').fadeIn('fast');
      }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <a href="">Titulo 1</a>
    <div class="texto">
      <p>
        Texto 1
      </p>
      <div class="readmore">Mostrar/Ocultar</div>
    </div>
  </li>
  <li>
    <a href="">Titulo 2</a>
    <div class="texto">
      <p>
        Texto 2
      </p>
      <div class="readmore">Mostrar/Ocultar</div>
    </div>
  </li>
</ul>

Imagine I have several li with the same elements div and p, which differ only in content.

I want to click on "admonish" and hide or display only the paragraph above it, but when I click it, jQuery displays or hides all the p page.

1 answer

2


There may be easier ways, but this way, if I understood correctly, I could do it this way:

$(document).on("click", ".readmore", function(e) {
   let el = $(this);
   if(el.parent().find('p').hasClass('mostrando')) {
      el.parent().find('p').removeClass('mostrando').hide();
   } else {
      el.parent().find('p').addClass('mostrando').show();
   }
})

You can see it working on jsfiddle.

  • That’s exactly what I was trying to do and failing, helped me and a lot!!! Thank you!!!

Browser other questions tagged

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