-1

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
  • remove the `div.main`. So change your second selector to `document.querySelector("div.user-panel.main input[name='login']")` – Nick Parsons Nov 25 '18 at 03:30

2 Answers2

2

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>
shkaper
  • 4,689
  • 1
  • 22
  • 35
0

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).

tshimkus
  • 1,173
  • 2
  • 17
  • 24