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

Question:

I have a div with the same classes repeating over and over in my page (it only changes the content) and I only want to select 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 that I have several li with the same div and p elements, which only differ in content.

I want to click "readmore" and hide or show just the paragraph above it, but when I click on it, jQuery shows or hides every p on the page.

Answer:

It may have easier ways, but this way, if I understood correctly, 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 in jsfiddle .

Scroll to Top