I am drawing a two-dimensional matrix with vanilla JavaScript and CSS, but I'm struggling to index coordinates of every element.
There are a couple of problems. If I put coordinates in class, for example,
class="_1 _2"
And then use either getElementsByClassName or querySelector, I will get both elements with and
My current solution is to use both class and id. I then reference with document.getElementsByClassName("_1")[1]
I wonder if you have any thought/suggestion about this?
Thank you
CodePudding user response:
Guess you could use data attributes like so:
const elements = document.querySelectorAll('[data-x="2"][data-y="1"]');
for (let el of elements) {
el.classList.add('selected');
}
table td {
width: 50px;
height: 50px;
margin: 2px;
background-color: green;
color: white;
}
.selected {
background-color: red;
}
<table>
<tr>
<td data-x="1" data-y="1">11</td>
<td data-x="1" data-y="2">12</td>
</tr>
<tr>
<td data-x="2" data-y="1">21</td>
<td data-x="2" data-y="2">22</td>
</tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Do you actually want to give them all named classes?
It is sometimes easier to use the position of elements - nth-child(1) for example - in this sort of situation as they can be accessed via integer calculations rather than having to make a string (or two) to match the classes.
Here's a trivial example:
function getEl(mx, row, column) {
return mx.querySelector(':nth-child(' (row - 1) * 2 column ')');
}
const matrix = document.querySelector('#matrix');
alert(getEl(matrix, 1, 2).innerHTML);
#matrix div:nth-child(odd) {
background: green;
}
<div id="matrix">
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>