Search code examples
jqueryjquery-traversing

Traverse up until find attribute id


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


Solution

  • 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>