so I have this problem that I want to compare 2 cells of Chess table that I did.
When I click on cell, I'm getting in console.log only td, and the comparison I'm using I have the cell itself (I added photo for example)
so there is other way to get the cell properties when click on it then the event.target.nodeName.toLowerCase()?
here in this function im sending cell and try to compare it to event.target.nodeName.toLowerCase()
the problem is, that in event.target.nodeName.toLowerCase() i have "td" and not the "cell" like shonw in the right side of the photo, so i want to know if there is other opetion whel im clicking on some cell of grid(chess table) that i can get the cell itself to be compared.
const handler= Click.bind(null, cell);
table.addEventListener("click", handler);
function Click(cell, event) {
if (event.target.nodeName.toLowerCase() === 'td' )
{
event.target.style.backgroundColor = "blue";
if (event.target.nodeName.toLowerCase() == cell])
{
alert("SOMETEXT")
}
}
}
You can get the target element classes with <Element>.classList and after check if it's a black or white cell according to its class.
<DOMTokenList>.contains is one of methods you can use to check if the element has a specific class in a mordern way, thanks to @CerebralFart and @Bergi.
document.onclick = e => {
const cell = e.target.classList.contains('blackcell')
? 'black'
: 'white';
console.log(cell);
}
<table>
<tr>
<td class="cell blackcell">B</td>
<td class="cell whitecell">W</td>
<td class="cell whitecell">W</td>
<td class="cell blackcell">B</td>
<td class="cell blackcell">B</td>
</tr>
</table>