Traverse up until find attribute id

19 views Asked by At

I have to traverse up until element have id attribute. My problem here is element is not definite and sometimes parent have id attribute, sometimes grandparent have id attribute like that goes on. I try like

var id = $(this).closest().find("['id']").attr("id");

i dont have such ideas to do this . Can anyone help me

1

There are 1 answers

0
CertainPerformance On BEST ANSWER

Try using the [id] selector string inside the .closest, so that closest returns the element with an ID. Note that the selector string shouldn't have "s around the id:

$('span').on('click', function() {
  var id = $(this).closest("[id]").attr("id");
  console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="outer">outer
  <div>inner
    <span>click here</span>
  </div>
</div>