CSS 在 Chrome 中嵌套 nth-child 的 querySelector 似乎不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6345358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
querySelector with nested nth-child in Chrome doesn't appear to work
提问by zacharyc
I've been looking at using nth-child within an nth-child selector to find an element. This appears to work in Firefox, but does not seem to be working on chrome. Here's my test file:
我一直在考虑在 nth-child 选择器中使用 nth-child 来查找元素。这似乎适用于 Firefox,但似乎不适用于 chrome。这是我的测试文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>untitled</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript" charset="utf-8">
myFunc = function() {
if(document.querySelector('#wonderful DIV:nth-child(2) DIV:nth-child(2)')) {
alert("found the element");
} else {
alert("element not found");
}
};
</script>
</head>
<body onLoad="myFunc()">
<div id="wonderful">
<div>
</div>
<div >
<div>
</div>
<div class="blue">
find me!
</div>
</div>
</div>
</body>
</html>
Has anyone else seen this issue? Have a solution to get around this?
有没有其他人看到过这个问题?有解决方案来解决这个问题吗?
回答by DanielB
This worked for me in chrome, but it does not work in FF then.
这在 chrome 中对我有用,但在 FF 中不起作用。
document.querySelector('#wonderful div:nth-child(2):nth-child(2)')
The following snipped works in both browsers, but I assume you know that already
以下剪辑在两种浏览器中都有效,但我假设您已经知道了
document.querySelector('#wonderful div:nth-child(2) div.blue')
So it looks like an implementation failure in chrome for me.
所以对我来说,它看起来像是 chrome 中的一个实现失败。
回答by Phrogz
Found this (very old) question while hunting down a red herring. This answer is to note: today, Chrome v73 works just fine. Snippet here proves it:
在追捕红鲱鱼时发现了这个(非常古老的)问题。这个答案需要注意:今天,Chrome v73 运行良好。这里的片段证明了这一点:
const sel = '#wonderful div:nth-child(2) div:nth-child(2)';
console.log(document.querySelector(sel))
<div id="wonderful">
<div></div>
<div>
<div></div>
<div class="blue">find me!</div>
</div>
</div>