admin管理员组

文章数量:1415460

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?

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?

Share Improve this question asked Jul 2, 2013 at 10:36 YodasMyDadYodasMyDad 9,49525 gold badges79 silver badges125 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 3

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

Try:

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

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 :)

use prev function in jquery

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

本文标签: javascriptGet Text Of Closest Parent H4 Using JqueryStack Overflow