Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parent element by specified tag name using jquery?

Tags:

jquery

parent

I want to get an Element's parent which has an specified tag name.

Sample code:

<table>    <tr>       <td>           <input type='button' id='myId' />       </td>    </tr> </table> 

Now i want something like this:

$('#myId').specificParent('table'); //returns NEAREST parent of myId Element which table is it's tagname. 
like image 557
rahim asgari Avatar asked Nov 15 '10 15:11

rahim asgari


People also ask

How do I find a specific parent in jQuery?

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.

How do you find the parent element name?

click(function() { var parent = this. parentElement; var tagName = parent.

Which jQuery method returns the direct parent element of the selected element?

jQuery parent() Method The parent() method returns the direct parent element of the selected element.

What is the difference between parent () and parents () methods in jQuery?

parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree. parents() method allows us to search through the ancestors of these elements in the DOM tree.


1 Answers

See .closest():

Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

I.e.,

$('#myId').closest('table') 

(Demo)

like image 200
jensgram Avatar answered Sep 24 '22 18:09

jensgram