when I put div.main as a separated condition the code doesn't work
<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
.
Since in your html it's just a single div with 2 classes, this selector doesn't find anything.
It would work, however, if your html was looking like this:
<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
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.