YodasMyDad
YodasMyDad

Reputation: 9485

Get Text Of Closest Parent H4 Using Jquery

I have several of these html blocks on a page in this structure

<div class="listing">
<h4><a href="#">Some test Entry here</a></h4>
<div class="entry clearfix">
    <a href="#" class="btn">
        Text Here                    
    </a>
</div>
</div>

I have the click event on the '.entry .btn' which is firing fine. But I want to get the inner text of the 'H4 a' within the same listing block as the btn I clicked. I have tried the following but just cannot seem to get the H4 text.

var getTitle = $(this).parents("h4").first();
alert(getTitle.html());

I have also tried closest() but still cannot get the H4? Any ideas?

Upvotes: 0

Views: 4493

Answers (3)

dreamweiver
dreamweiver

Reputation: 6002

Firstly You need to traverse upwards in the DOM structure to identify the target element using .parent() or .parents() functions.

For your requirement you dont need the immediate parent hence .parent() is of no use instead you need to use .parents() to get all the ancestors in the DOM and refer the one with class selector .listing & finally traverse inward to find the target element h4.

JS CODE:

$('.btn').on('click',function(){
   alert($(this).parents('.listing').find('h4').html());
});

Live Demo @ JSFIDDLE

Happy Coding :)

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

use prev function in jquery

var getTitle = $(this).prev().find("h4").first();
alert(getTitle.html());

Upvotes: 1

user405398
user405398

Reputation:

closest & parents looks for ancestors. But, h4 is in another children of parent .listing.

Try:

var getTitle = $(this).closest('.listing').find("h4").first();

Upvotes: 3

Related Questions