开发者

jQuery - Getting the second level parent of an element

I am trying to retrieve the parent of an <a> element's parent (grandparent?). I want to find that grandparent, then find a <b> tag in that element, then store that text as a 开发者_运维知识库variable to publish elsewhere on the page. I've been trying to use the parent() function but without success.

Here's the code I tried:

    $('.mixPlayCell a').click( function() {
        var title = $(this).parent().get(0).parent().get(0).text();
        alert(title);
    });


For selecting a second parent

parents(':eq(1)')

looks smoother than

parent().parent()

Also, you might find that

closest('ul')

fits the job better.


try:

$(this).parent().parent().find('.thingtofind').text();


parents() returns a list, so this works:

$(this).parents()[1];


$('.mixPlayCell a').click(function() {
  elem = $(this).parent().parent();
  title = $("tag selector goes here",elem).html();
});

Something like this?


There is only 1 parent, no need to .get(0)

    var title = $(this).parent().parent().find("whateveryouwant").html();


$(this).parent().parent().find('mytag').text()

Should work just fine.

You can use any selector in the find method. If you'll just need to search in the direct children of the grandparent's element, you can also use $.children instead of find which searches in all of the element's children.


Try this for simple implementation :

$('.mixPlayCell a').click( function() {
    var title = $(this).parents().text();
    alert(title);
});

Just changed .parent() with one .parents()

this is works for every jQuery versions.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜