I am trying to use:
document.querySelectorAll('[data-r=0 data-c=0]');
to select a specific HTML element but it returns:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '[data-r=0 data-c=0]' is not a valid selector.
I'm trying to understand why. Is it not query by 2 datasets at once? All the examples I've found online only show examples of querySelectorAll with only one dataset in them. I'm trying to avoid using JQuery, is there any way?
<table id="board">
<tr>
<td class="box" data-r=0 data-c=0></td>
<td class="box" data-r=0 data-c=1></td>
<td class="box" data-r=0 data-c=2></td>
</tr>
<tr>
<td class="box" data-r=1 data-c=0></td>
<td class="box" data-r=1 data-c=1></td>
<td class="box" data-r=1 data-c=2></td>
</tr>
<tr>
<td class="box" data-r=2 data-c=0></td>
<td class="box" data-r=2 data-c=1></td>
<td class="box" data-r=2 data-c=2></td>
</tr>
</table>
First of all, you need to add quotes so that the selector can be valid. Then depending on what you actually want to select, you have two different syntaxes:
[data-r="0"][data-c="0"]
will select elements that have data-r=0
AND data-c=0
[data-r="0"],[data-c="0"]
will select elements that have data-r=0
OR data-c=0
The first behaviour is pretty well described in the standard documentation. The second one is simply a selector list. Of course, you can combine those. For example, you could select the diagonal of your table by using [data-r="0"][data-c="0"], [data-r="1"][data-c="1"], [data-r="2"][data-c="2"]
.
// Matches 1 element
console.log(document.querySelectorAll('[data-r="0"][data-c="0"]'));
// Matches 5 elements
console.log(document.querySelectorAll('[data-r="0"],[data-c="0"]'));
// Matches the 3 diagonal elements
console.log(document.querySelectorAll('[data-r="0"][data-c="0"], [data-r="1"][data-c="1"], [data-r="2"][data-c="2"]'));
<table id="board">
<tr>
<td class="box" data-r=0 data-c=0></td>
<td class="box" data-r=0 data-c=1></td>
<td class="box" data-r=0 data-c=2></td>
</tr>
<tr>
<td class="box" data-r=1 data-c=0></td>
<td class="box" data-r=1 data-c=1></td>
<td class="box" data-r=1 data-c=2></td>
</tr>
<tr>
<td class="box" data-r=2 data-c=0></td>
<td class="box" data-r=2 data-c=1></td>
<td class="box" data-r=2 data-c=2></td>
</tr>
</table>