I am trying to learn jquery and have a question -
The div element on the page looks like -
<div id ="1">
<p id="first"> one
<p id="second"> one.one
<p id="third"> one.one.one </p>
</p>
</p>
</div>
Both the below selectors are giving me the same result -
$('div p').css({'background-color' : 'blue'});
$('div>p').css({'background-color' : 'blue'});
Shouldn't the second selector just return only the first <p> tag of the <div> element ?
$('div p') selects all <p> tags that are descendants of a <div>.
$('div>p') only selects <p> tags that are direct children of a <div>.
What's happening in your code is since the closing </p> tag is optional, the browser is reading your HTML as having 3 <p> (actually 5, since the last 2 closing tags are being "mis-read") tags that are all siblings.
So, it's being read as:
<div id ="1">
<p id="first"> one</p>
<p id="second"> one.one</p>
<p id="third"> one.one.one</p>
<p></p>
<p></p>
</div>
That's why they all became blue. $('div>p') matched them all, since they are all direct children of the <div> (or that's what the browser thinks).
Demo: http://jsfiddle.net/wP7uD/
Open your browser's dev tools and inspect the DOM, you'll see that there are 5 <p> tags.
Moral of this: You cannot have <p> tags as children of <p> tags.
W3C spec for <p> tags: http://www.w3.org/TR/html-markup/p.html
All the <p> are children of the first <p> element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With