开发者

jQuery: Only select first level childnodes

I'm trying to get something to work what should be fairly easy with jQuery. All I want is to select the sibblings of the selected node, and NOT the children of a sibbling!

<div id="test">
    <p>First Paragraph
        <p class='border2'>SUB paragraph
            <p class='border3'>SUB SUB paragraph</p>
开发者_开发技巧        </p>
    </p>
    <p>Second Paragraph</p>
    <p>Third Paragraph</p>
    <p>Fourth Paragraph</p>
</div>

At this moment I've tried a lot of different things, but they are not behaving as expected. I tried e.g.:

  • $("div").find("p").andSelf().addClass("border");
  • $("div > p").addClass("border");
  • $("div p:first").nextAll().andSelf().addClass("border");
  • $("#test ~ p").addClass("border");

My code snippet can be found at jsFiddle.


You won't be able to because your markup is invalid.

You can't have a <p> nested in a <p> so the browser is kicking the nested ps out.

Here's your fiddle but with updated CSS to show that they're no longer nested.

You can only nest inline elements in a <p>.


Your problem is caused because

The P element represents a paragraph. It cannot contain block-level elements (including P itself).

Taken from The Specs.

The browsers consider each paragraph as a direct child of the original div, as it cannot be contained within a different p. You chose the wrong element to mess with :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜