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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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

Questions:
Answers:
$('#myId').closest("table");

Questions:
Answers:

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