user2310422
user2310422

Reputation: 555

Selecting Parent's Sibling's content

Below is the code I am working on, my goal is, whenever the user click the link with a class "click_me", I would like to alert the content of it's parent's siblings, which is "Hello Friends" or "How are you?".

I've tried doing the code below, but it didn't work.

 $('.click_me').click(function(event){
                    alert($(this).parent('div').closest('p').html());
                });



<li>
    <div>
        <a href="#" class="click_me">Click Me</a>
    </div>
    <p>Hello Friends!</p>
</li>


<li>
    <div>
        <a href="#" class="click_me">Click Me</a>
    </div>
    <p>How are you?!</p>
</li>

Upvotes: 0

Views: 40

Answers (2)

PSL
PSL

Reputation: 123739

You can use next to select the next element of its parent. Issue with your selector is that you are looking upwards using closest which tests itself and up the DOM tree.

alert($(this).closest('div').next().html());

Fiddle

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

.closest() will look for only the ancestor elements, in your case the p element is not an ancestor element, it is a sibling

you need to use siblings()

alert($(this).parent('div').siblings('p').html());

Demo: Fiddle

or in this case it is the next element use .next()

alert($(this).parent('div').next('p').html());

Demo: Fiddle

Upvotes: 2

Related Questions