开发者

why is this fiddle giving a result of 4?

开发者 https://www.devze.com 2023-03-31 02:55 出处:网络
http://jsfiddle.net/sushilbharwani/zWgNX/ I am trying to understand the > selector i want to know why the fiddle gives the size of 4. 2 was what i was thinking of. 3 could have been a possibilty but w

http://jsfiddle.net/sushilbharwani/zWgNX/ I am trying to understand the > selector i want to know why the fiddle gives the size of 4. 2 was what i was thinking of. 3 could have been a possibilty but why 4.

HTML:

<div class="ban_h开发者_如何学编程dr">
    <p>
        Which of the following are correct? abc abc
        <p>Test this code</p>
    </p>
<p>Which of the following are correct? pqr pqr</p>
</div>

jQuery:

alert($('div.ban_hdr > p').size());


I pulled up the source in Chrome's Developer Tools, and here's at least how Google Chrome interprets your source:

<div class="ban_hdr">
    <p>
        Which of the following are correct? abc abc
    </p>
    <p>Test this code</p>
    <p></p>
    <p>Which of the following are correct? pqr pqr</p>
</div>

A <p> tag can't be nested in a <p> tag. So, this is apparently Chrome's best interpretation of what you meant. Go figure. When you use invalid code, expect nonsensical results.


Since your P tags are nested (which they aren't allowed to), the browser rearranges them to:

<p> Which of the following are correct? abc abc </p>
<p>Test this code</p>
<p></p>
<p>Which of the following are correct? pqr pqr</p>

It's now easy to see why the result is 4.


You can't nest p tags. The rendered output of this HTML is:

<div class="ban_hdr">
    <p>
        Which of the following are correct? abc abc</p> <!-- 1 -->
        <p>Test this code</p> <!-- 2 -->
    <p></p> <!-- 3 -->
<p>Which of the following are correct? pqr pqr</p> <!-- 4 -->
</div>
0

精彩评论

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

关注公众号