so i have another JavaScript question how can I alter the following
- Code: Select all
<script>
function hoveron(event) {
var target = event.target.parentNode;
target.style.cssText = "background-color:red";
}
function hoveroff(event) {
var target = event.target.parentNode;
target.style.cssText = "";
}
var cells = document.querySelectorAll("td");
for (i = 0; i < cells.length; i++) {
cells[i].addEventListener("mouseover", hoveron);
cells[i].addEventListener("mouseout", hoveroff);
}</script>
So that it will always get the table row regardless of how many children there are ?
See if I have a table like this
- Code: Select all
<table>
<tr>
<td>item 1</td>
<td>item 2</td>
</tr>
</table>
Everything works as expected and when I hover over one of the TDs the whole row is highlighted however if I add anchor tags then the above script brakes and instead of highlighting the row that is being hovered it highlights the TD
Now i know i could give each row an ID and then just do document.getElementById("id"); and that would probably do the trick but i feel like there has to be a cleaner way to do this there has to be some way to make the script always select the row closest to where the hover event happened.
i tried changing
- Code: Select all
var target = event.target.parentNode
to
- Code: Select all
var target = event.target.closest('tr');
but it doesn't appear to work, so i can only assume I'm misunderstanding how to use it and almost everything I'm finding seems to be for jquery which is neither use nor ornament to me when I'm trying to learn JavaScript.