jQuery: Show / Hide DIV within a specific element

2

I'm having a question in jQuery:

I have the following code inside a page, where the "description-img" DIV repeats more than once:

<div class="description-img">
   <div class="confirmacao" style="display: block; ">
      <p class="votoMsg">VOCÊ VOTOU!</p>
      <span class="name"><a hreh="#" id="linkShare">Share Design</a>
         <div id="share" style="display:none;">Links para compartilhamento</div>
      </span>
   </div>
</div>

<div class="description-img">
   <div class="confirmacao" style="display: block; ">
      <p class="votoMsg">VOCÊ VOTOU!</p>
      <span class="name"><a hreh="#" id="linkShare">Share Design</a>
         <div id="share" style="display:none;">Links para compartilhamento</div>
      </span>
   </div>
</div>

When I use the jQuery show () / hide () to show / hide the "#share" div by clicking "#linkShare", it takes all divs from the page. How do I get exactly the DIV that is inside each corresponding block?

Thank you very much for the light!

    
asked by anonymous 23.08.2014 / 16:47

2 answers

3

The ID parameter is used to identify a specific element and can not be repeated, to identify elements that must appear multiple times, use a class. And to identify the element that is firing the event, use $(this) , below a quick example:

HTML:

<div class="description-img">
   <div class="confirmacao" style="display: block; ">
      <p class="votoMsg">VOCÊ VOTOU!</p>
      <span class="name"><a hreh="#" class="linkShare">Share Design</a>
         <div class="share" style="display:none;">Links para compartilhamento</div>
      </span>
   </div>
</div>

Jquery:

$('.linkShare').click(function() {
    //$(this) é o .linkShare clicado
    //.siblings('.share') é .share irmão do .linkShare clicado (estão dentro do mesmo span)
    $(this).siblings('.share').show();
});

See working on JSFiddle

    
23.08.2014 / 17:00
1

Being a bit more specific than the colleague above and reinforcing what Patrick said, when repeating elements do not use id, but classes !!! Use find to find a specific element, in this case use this to indicate the element clicked if you move in the DOM as you prefer you can use .find or. siblings, I believe that in this case .siblings is more elegant =] but I did with the parent below to illustrate the use of .find

<script>
    $(function(){
        $('.linkShare').click(function(){
            $(this).parent().find('.share').toggle("slow");
        });

    });

</script>

<div class="description-img">
   <div class="confirmacao" style="display: block; ">
  <p class="votoMsg">VOCÊ VOTOU!</p>
  <span class="name"><a href="#" class="linkShare">Share Design</a>
     <div class="share" style="display:none;">Links para compartilhamento</div>
    </span>
   </div>
</div>   
    
23.08.2014 / 17:26