Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the parent element using javascript

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?

like image 272
Achaius Avatar asked Mar 16 '10 12:03

Achaius


People also ask

How do you find the parent element of a class?

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.

How do you check if an element is a child of a parent in JavaScript?

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); };

What is parent in JavaScript?

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.

Which is the parent element?

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>.


2 Answers

Using plain javascript:

element.parentNode 

In jQuery:

element.parent() 
like image 62
Yuval Adam Avatar answered Sep 25 '22 00:09

Yuval Adam


Use the change event of the select:

$('#my_select').change(function()
{
   $(this).parents('td').css('background', '#000000');
});
like image 26
ryanulit Avatar answered Sep 24 '22 00:09

ryanulit