About querySelector() with multiple selectors

Viewed 15582

I had a situation in which I wanted to focus either an input tag, if it existed, or it's container if it didn't. So I thought of an intelligent way of doing it:

document.querySelector('.container input, .container').focus();

Funny, though, querySelector always returns the .container element.

I started to investigate and came out that, no matter the order in which the different selectors are put, querySelector always returns the same element.

For example:

var elem1 = document.querySelector('p, div, pre');
var elem2 = document.querySelector('pre, div, p');

elem1 === elem2; // true
elem1.tagName;   // "P".

My question is: What are the "reasons" of this behavior and what "rules" (if any) make P elements have priority over DIV and PRE elements.

Note: In the situation mentioned above, I came out with a less-elegant but functional solution:

(document.querySelector('.container input') ||
 document.querySelector('.container')       ).focus();
4 Answers

You can try selecting all elements with document.querySelectorAll("p.a, p.b") as shown in the example below and using a loop to focus on all elements that are found.

<html>
<body>
<p class="a">element 1</p>
<p class="b">element 2</p>

<script>
var list=document.querySelectorAll("p.a, p.b");
for (let i = 0; i < list.length; i++) {
  list[i].style.backgroundColor = "red";
}
</script>
</body>
</html>
Related