I want to change the background color of the table cell when radio button inside the cell is clicked.
<table>
<tr>
<td align="center">
<input type="radio" value="foo"
onclick="this.parentElement.style.background-color='red';" />
</td>
</tr>
</table>
How to get the parent element reference?
Use the closest() method to get the closest parent element by class, e.g. child. closest('. parent') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.
To check if an element is a child of a parent with JavaScript, we can use the parent element's contains method. const contains = (parent, child) => { return parent !== child && parent. contains(child); };
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
A parent is an element that is directly above and connected to an element in the document tree. In the diagram below, the <div> is a parent to the <ul>. A child is an element that is directly below and connected to an element in the document tree. In the diagram above, the <ul> is a child to the <div>.
Using plain javascript:
element.parentNode
In jQuery:
element.parent()
Use the change event of the select:
$('#my_select').change(function()
{
$(this).parents('td').css('background', '#000000');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With