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?
3 Answers
Reset to default 3closest
& 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
版权声明:本文标题:javascript - Get Text Of Closest Parent H4 Using Jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745184333a2646611.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论