我真的不明白为什么下面的选择器会按预期工作(即获取 td
):
table tr td
但这个不是:
table > tr > td
td
是 tr
的后代,后者又是 table
的后代,但它们也是彼此的子代。因此,我认为 >
选择器也可以。
我做了两个 fiddle :
为什么 >
选择器在这里不起作用?
最佳答案
在 HTML 中,浏览器隐式添加一个 tbody
元素,其中包含 tr
元素1,所以实际上,tr
永远不是 table
的子项。
因此,您必须改为这样做:
table > tbody > tr > td
当然,如果您自己添加一个tbody
元素,您将使用相同的选择器。 spec解释何时隐式添加 tbody
否则:
Tag omission
A
tbody
element's start tag may be omitted if the first thing inside thetbody
element is atr
element, and if the element is not immediately preceded by atbody thead
, ortfoot
element whose end tag has been omitted.
1 对于正确用作application/xhtml+xml
的 XHTML 文档,情况并非如此,但是,given its XML roots .
关于html - 为什么在使用子选择器时 table > tr > td 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5568859/