为什么我的第 n 个子选择器选择了错误的元素?

Why is my nth-child selector selecting the wrong element?

我有这个元素树(从 Stack Overflow 的 404 页面偷来的):

当我们看它时,突出显示的<div>应该是第四个元素。但是,在$('body > div:nth-child(4)') returns div 之前。为什么会这样?是否以某种方式在 <noscript> 标签中选择了 div?当我删除 <noscript> 时,它会正确选择。

为什么会这样?

div:nth-child(4) 不给你第 4 个 div,它给你一个既是 div 又是第 4 个 child 的元素(如果第 4 个 child 不是 div;这就是为什么您没有得到 div:nth-child(1) 的任何东西的原因)。您想要的第 4 个 div 是带有 <noscript> 的第 5 个 child,没有它的第 4 个 child。

来自 jQuery docs:

The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.

所以,如果你想要第 4 个 div,你会做 body > div:eq(3)

尝试将 div:nth-child(4) 更改为 div:nth-child(5) 我已经测试过了,它适用于第 5 个 child 而不是第 4 个 child。第 4 个 child 它会选择您想要的第一个 <div>

this post

[第 1 步]

:nth-child()

Selects all elements that are the nth-child of their parent.

jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification

W3C 规范 here

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree

所以这里 :nth-child(4) 呈现完整形式 :nth-child(0n+4),并表示一个元素在文档树中正好有 3 个兄弟姐妹

无脚本标签

this post

如果启用 javascript,<noscript> 标记可能不会呈现,但仍可以使用 nextSiblingprevSibling 访问,因此它会用 nth-child 计数

[第 2 步]

body > div:nth-child 结合,就像其他 pseudo-classes 一样,例如a:hovertr:hover:hover不关心是a还是tr标签,只是特殊select或

[整件事]

body>div:nth-child(4) 首先 select body>div,然后 select div 恰好有 3 兄弟姐妹在它之前,所以 <noscript> 标记计数。