Change properties of a single element that repeats multiple times on my page

3

I have 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><ahref="">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 that I have multiple li with the same elements div and p , which differ only content.

I want to click on readmore and hide or display only the paragraph above it, but when I click on it, jQuery displays or hides all% of the page

    
asked by anonymous 27.10.2018 / 18:50

1 answer

2

I might have easier ways, but this way, if I got it right, I could do it like this:

$(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 at jsfiddle .

    
27.10.2018 / 19:55