Wednesday, 16 November 2016

jquery selector confusion - $('div p') vs $('div>p')



I am trying to learn jquery and have a question -



The div element on the page looks like -




one

one.one

one.one.one







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

tag of the

element ?


Answer



$('div p') selects all

tags that are descendants of a

.



$('div>p') only selects

tags that are direct children of a

.






What's happening in your code is since the closing

tag is optional, the browser is reading your HTML as having 3

(actually 5, since the last 2 closing tags are being "mis-read") tags that are all siblings.



So, it's being read as:




one


one.one


one.one.one







That's why they all became blue. $('div>p') matched them all, since they are all direct children of the

(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

tags.



Moral of this: You cannot have

tags as children of

tags.






W3C spec for

tags: http://www.w3.org/TR/html-markup/p.html


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...