i-CONICA
i-CONICA

Reputation: 2379

jQuery get contents to closest H3 tag

I'm trying to get the content of a H3 tag closest to my selected element.

$(this).closest('h3').html();

The code above contains null when run, "this" is definitely the selector of another element in the same parent element as the h3.

Can someone offer an idea as to why it won't work?

Thanks.

Upvotes: 0

Views: 4371

Answers (2)

Jezen Thomas
Jezen Thomas

Reputation: 13800

jQuery also has the methods .next() and .prev(), just in case you know which direction the h3 is in relation to $(this).

For example:

$(this).click(function(){
    $(this).next('h3').html('a string');
});

Upvotes: 1

James Allardice
James Allardice

Reputation: 166031

"this" is definitely the selector of another element in the same parent element

That's your problem. closest looks up the DOM tree, not along it at siblings. Use siblings instead:

$(this).siblings('h3').html();

Note that this will return the HTML of the first h3 sibling. If there are more you will probably want to specify the correct one.

Upvotes: 5

Related Questions