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

JqueryParent

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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)

Solution 2 - Jquery

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

Solution 3 - Jquery

$('#myId').parents('table') works as well

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrahim asgariView Question on Stackoverflow
Solution 1 - JqueryjensgramView Answer on Stackoverflow
Solution 2 - JqueryNimChimpskyView Answer on Stackoverflow
Solution 3 - JquerydonahView Answer on Stackoverflow