alias51
alias51

Reputation: 8608

How to select child element of sibling in jquery

I have the following HTML:

<div class="col-md-4">

    <div class="participant" id="participant-1">

        <div class="caller">
            <img src="public/img/caller.png" class="img-circle transparent">
        </div>

        <div class="more"><img src="public/img/more.png"></div>


    </div>
</div>

I am trying to toggle the transparent img class when "more" is clicked.

I have the following code:

$(this).siblings(".caller > img.img-circle").toggleClass("transparent");

Where am I going wrong? I want to ensure that the toggle only affects the class inside the same parent (HTML is repeated elsewhere).

Upvotes: 0

Views: 2246

Answers (4)

Ben Jackson
Ben Jackson

Reputation: 11922

You're going wrong because you seem to be assuming that .siblings() will process the selector in some way and traverse down from the generation of .more to find the .img-circle element. That's not how it works.

.siblings() will look for a sibling matching the passed selector; in your case this is ".caller > img.img-circle", and the .more element doesn't have any siblings matching that. Therefore, your call to .siblings() is returning empty.

As others have pointed out, you can use something like:

$(this).siblings('.caller').find('.img-circle').toggleClass('transparent');

for reference: http://api.jquery.com/siblings/

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use .prev(), it gets the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

$(this).prev().find("img.img-circle").toggleClass("transparent");

if you want to use .siblings() then

$(this).siblings(".caller").find("img.img-circle").toggleClass("transparent");

Upvotes: 0

you can try

 $(this).parent().find(".caller > img.img-circle").toggleClass("transparent");

Live DEmo

Upvotes: 0

RafH
RafH

Reputation: 4544

try

$('.more').on('click', function(e) {
   $(this).parent().find('.img-circle').toggleClass("transparent"); 
});

Working exemple : http://jsfiddle.net/yiernehr/B2Bcf/1/

Upvotes: 1

Related Questions