Anonymous
Anonymous

Reputation: 77

Get closest unknown id

I'm trying to get something easy, but can't make it work.

HTML

<div id="test">
    <p>
        Super <i>cool</i>
    </p>
</div>

or

<div id="test">
    <table>
        <tr>
            <td>Super <i>cool</i></td>
        </tr>
    </table>
</div>

My idea is quite simple: click on <i> tag console.log the parent id. As you see sometime it's the direct parent, sometime it can be a parent from 13 nodes above.

I was looking something with closest() or parents() maybe?

Upvotes: 0

Views: 184

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

I was looking something with closest() or parents() maybe ?

You were on the right track. If the i won't have an id, then:

var test = $(this).closest("[id]");

...which says, find me the closest element (starting with this) that has an id attribute.

If the i may have an id (you haven't shown one) and you don't want it, then you probably want

var test = $(this).parents("[id]").first();

or

var test = $(this).parent().closest("[id]");

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337590

Assuming you're attempting to get the closest parent element that has an id attribute you can use closest() with the attribute selector:

$('i').click(function() {
  var id = $(this).closest('[id]').prop('id');
  console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test-01">
  <p>
    Super <i>cool</i>
  </p>
</div>

<div id="test-02">
  <table>
    <tr>
      <td>Super <i>cool</i></td>
    </tr>
  </table>
</div>

Upvotes: 2

Related Questions