开发者

jquery get children of children of children [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

Okay, this may be a bit basic. The HTML is :

<div class="parents-of-all">
<p>
    <a>
        <span class="thechild">Something</span>
    </a>
</p>

The jquery 开发者_如何学Pythonis

$('.parents-of-all').click(function(){
    alert($(this).find('span').attr('class'));
});

But somehow it doesn't work. Test it here :

http://jsfiddle.net/3zn7e/1/

My question is how can I traverse to the span? My usual way is

$(this).children().children().children().attr('class');

I'm sure there are shorter ways than this and using find() is one of them, but I can't seem to make it work.

Many thanks!

EDIT : DUH! Apparently I forgot the . for the parents-of-all DOM selector. Sometimes the simplest error is right there in your face.

But again, is there any difference between using find() and multiple children() ? I find using multiple children() ensures more accurate traversing since we can add elements selector if we want, but any other major difference?


You were missing the dot in your class selector:

$('.parents-of-all').click(function(){
    alert($(this).find('span').attr('class'));
});

http://jsfiddle.net/BoltClock/3zn7e/2


If you are looking to change an attribute on the children-with-ancestor or children-with-parent, you should use the respective selector:

  • decendant selector
  • child selector

For example:

$('.parents-of-all span').addClass('hello');

Would apply the class "hello" to all <span> elements that are descendants of an element of class parents-of-all.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜