jquery get children of children of children [closed]
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
.
精彩评论