In this example, the querySelectorAll selects td
elements 2 through 4:
document.querySelectorAll("td + td");
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
So, it's going to select all td
elements greater than or equal to 2.
But in the following example, 'div'
is not selecting both of my div
elements when I use:
document.querySelectorAll('div').style.color = 'red';
<div>foo</div>
<div>bar</div>
Demo
Why doesn't querySelectorAll work in this basic scenario?
In this example, the querySelectorAll selects td
elements 2 through 4:
document.querySelectorAll("td + td");
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
So, it's going to select all td
elements greater than or equal to 2.
But in the following example, 'div'
is not selecting both of my div
elements when I use:
document.querySelectorAll('div').style.color = 'red';
<div>foo</div>
<div>bar</div>
Demo
Why doesn't querySelectorAll work in this basic scenario?
NodeList
, which acts like an array.
– Evan Trimboli
Commented
Jul 7, 2014 at 10:43
querySelectorAll returns an array-like object (NodeList), so you can't set the property of all matched elements like that (like jQuery). You have to iterate over them:
var divs = document.querySelectorAll('div');
for(var i=0; i<divs.length; i++){
divs[i].style.color = "red";
}
Note: this differs from querySelector, which by contrast always returns a single element.
You can write a helper function like:
function qsa(selector, styleProperty, value){
var divs = document.querySelectorAll('div');
for(var i=0; i<divs.length; i++){
divs[i].style[styleProperty] = value;
}
return divs;
}
Usage:
var divs = qsa('div', 'color', 'red');