Using jQuery 1.4.2 (IE8 in compatibility mode)
Given the following structure:
<div id='something'>something</div>
<div id='parental'>
<div><p>hi there</p> goats</div>
<p>hello again</p>
</div>
<div> end of the line</div>
and this code:
var Fred= $('#parental');
$('div').css({color: 'blue'});
Fred.children('div').css({color: 'red'});
Fred.children('div').children('p').css({color:'green',border:'solid red 2px'});
Fred.children('div p').css({color: 'orange'});
Fred.children('div>p').css({border:'solid #FFFF00 2px'});
- “something” and ” end of the line” are blue as I would expect
- “goats” is red as I would expect.
- “hi there” is green with red border (I expected it to be orange/yellow border)
- “hello again” is orange with yellow border (not what I expected).
Why do the Fred.children('div p') selector and the Fred.children('div').children('p') and Fred.children('div>p') not select the same thing?
See it in action here: http://jsfiddle.net/bxAzN/
Because
.children()does the following:Now take
div p. The only children of#parentalare adivand apelement..children('div p')only matches thepelement as it has adivas ancestor (#parentalitself). But thedivchild clearly not matches this selector.You should think about
children()as get all children filtered by this selector which is different from get all descendants that match this selector. For this you would have to usefind().Fred.children('div').children('p')in contrast first takes alldivchildren ofFredand then selects all thediv‘spchildren.