开发者

Get url from previous h2 a element using jQuery

Using jQuery, while in the span element, without knowing post-383 id and class, how can I retrieve the url within the h2 a element?

The html code:

开发者_开发技巧<div id="post-1383" class="post-1383>
<h2 class="entry-title">
<a href="http://example.com/soul-music/">Soul Music</a>
</h2>
<span class="btn"></span> 
</div>

Something like this?

$('.btn').previous('a').attr('href');

Thanks!


You can do it using .prev() and .find() or .children(), like this:

$('.btn').prev('h2').find('a').attr('href');

You can give it a try here. The <a> isn't a sibling so .prev() won't won't work, you have to go back to the <h2> which is a sibling, then go inside it to get the <a> itself.


Close. Really close. You could use the jQuery traversal function .prev() to get the previous element. If you pass a string with the type of element you want it will give you your answer. so something like $('.btn').prev('a') should do the trick. But yeah you had it!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜