[英]why does the first code work and the second doesn't work?
when I put div.main as a separated condition the code doesn't work 当我将div.main作为单独的条件时,代码不起作用
<div class="user-panel main">
<input type="text" name="login">
</div>
document.querySelector("div.user-panel.main input[name='login']").style.backgroundColor = "red"; // this code works
document.querySelector("div.user-panel div.main input[name='login']").style.backgroundColor = "red"; // this code doesn't work
When your selectors are combined with a space - a descendant combinator - it's called a descendant selector. 当选择器与一个空格( 后代组合器) 组合在一起时 ,它称为后代选择器。 So
所以
document.querySelector("div.user-panel div.main input[name='login']")
is looking for a input[name='login']
inside a div.main
inside a div.user-panel
. 正在
div.user-panel
内的div.main
内寻找input[name='login']
。
Since in your html it's just a single div with 2 classes, this selector doesn't find anything. 由于在您的html中,它只是一个具有2个类的div,因此此选择器无法找到任何内容。
It would work, however, if your html was looking like this: 但是,如果您的html看起来像这样,它将起作用:
<div class="user-panel">
<div class="main">
<input type="text" name="login">
</div>
</div>
A space in a query selector denotes one element is inside another. 查询选择器中的空格表示一个元素在另一个元素内部。 The second line is looking for
input[name='login']
contained in div.main
, which is contained within another div ( div.user-panel
). 第二行正在查找
div.main
包含的input[name='login']
,该输入包含在另一个div( div.user-panel
)中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.