Asking this question because while it has been solved with JQuery on here, I didn't see any JavaScript solutions for it.
I have a simple table with a structure like so:
```
<tr>
<td><input type="checkbox"></td>
<td></td>
</tr>
```
For some reason, my javascript function to highlight the entire row is not working:
```
var rowElement = document.querySelector('tr');
rowElement.addEventListener('click', function(e){
var clickedElement = e.target; // this is checking what was the target element that is being clicked on, and that could be the checkbox inside the row
var clickedElementName = clickedElement.tagName.toLowerCase(); // we need to get the name to see if the element was an input element, using toLowerCase because those names are often uppercase
if ( clickedElementName === 'input' && clickedElementName.checked ) {
// if the clicked element is an input element, and is checked, meaning it's a checkbox, do the following:
this.style.color = "blue"; // 'this' is the element that we are listening on, that is, the rowElement
}
})
```
please use this code:
var rowElement = document.querySelector('tr'); rowElement.addEventListener('click', function(e){ var clickedElement = e.target; // this is checking what was the target element that is being clicked on, and that could be the checkbox inside the row var clickedElementName = clickedElement.tagName.toLowerCase(); // we need to get the name to see if the element was an input element, using toLowerCase because those names are often uppercase if ( clickedElementName === 'input' && clickedElement.checked ) { // if the clicked element is an input element, and is checked, meaning it's a checkbox, do the following: clickedElement.parentNode.parentNode.style.background = "blue"; // 'this' is the element that we are listening on, that is, the rowElement }else{ clickedElement.parentNode.parentNode.style.background = ""; } })
<table> <tr><td><input type="checkbox"/></td><td>cell</td></tr> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.