When you click on the button within a row, every TD should receive a class except for the first one.
To achieve this, update the onClick
bindings in your current code to preserve the context of the button being clicked. It is recommended to bind the events using addEventListener("click", addClasses);
The function addClasses
can utilize the current context to navigate back to the parent of the td
node and access the firstElementChild, skip it, and then iterate through the remaining children to apply the necessary class using classList.add
If classList
is not supported across all versions or element types in Internet Explorer, you can utilize element.className as an alternative
function addClasses() {
var node = this.parentNode.parentNode.firstElementChild || this.parentNode.parentNode.firstChild;
// Ensure first Child Selected is an element
while(node && node.nodeType !== Node.ELEMENT_NODE){
node = node.nextElementSibling || node.nextSibling;
}
//skip first element child
node = node.nextElementSibling || node.nextSibling;
// loop through all children adding a class
while (node && node.nodeType === Node.ELEMENT_NODE && node !== this) {
if(node.classList && node.classList.add){
node.classList.add("highlight");
} else {
node.className += " highlight"
}
node = node.nextElementSibling || node.nextSibling;
}
}
.highlight {
background-color: yellow;
}
<table>
<tr>
<td>1</td>
<td>joe</td>
<td>brown</td>
<td><button onclick="addClasses.call(this)">Add Class to add TD's in this TR except the first one</button></td>
</tr>
<tr>
<td>2</td>
<td>bob</td>
<td>blue</td>
<td><button onclick="addClasses.call(this)">Add Class to add TD's in this row except the first one</button></td>
</tr>
</table>
Regarding firstElementChild || firstChild
in the provided code snippet:
firstElementChild
may not be available in all versions and element types in IE. In such cases, you should use
firstChild
instead. However, keep in mind that firstChild
doesn't solely select the first
element node but also any #text
or #comment
nodes, etc.
To ensure proper skipping of the first td
element, consider looping through the nodes starting from the firstChild
(which could be a non-element like #Text
) and checking the nodeType
to exclude non-element nodes before reaching the actual element.