I am making a Table.
document.querySelector('table').addEventListener('click', (e) => {
console.log(e.target);
console.log(e.target.dataset.item);
})
td {
padding: 8px;
border: 1px solid black;
background-color: blue;
}
span {
background-color: red;
padding: 4px;
}
<table>
<tr>
<td data-item="item1"><span>1</span></td>
<td data-item="item2"><span>2</span></td>
<td data-item="item3"><span>3</span></td>
<td data-item="item4"><span>4</span></td>
<td data-item="item5"><span>5</span></td>
</tr>
</table>
When I click the BLUE PART, I can get data-item
attribute. But when I click the RED PART, I can't.
I wanna fix it, if I click <span/>
in <td/>
, I want to get data-item
attribute from <td />
.
e.target.closest("[data-item]").dataset.item
, if supported. – Stoneman