jQuery : Get first closest "parent" by type?

夏期劇場 picture 夏期劇場 · Aug 1, 2016 · Viewed 10.2k times · Source

I need to get the id of the first closest (nearest) li parent element when i click on a element.

<ul>
    <li id="wrong1">
        <ul>
          <li id="p1">
            <a href="" class='btn'></a>
          </li>
          <li id="p2">
            <a href="" class='btn'>Click here!</a>
          </li>
          <li id="p3">
            <a href="" class='btn'></a>
          </li>
        </ul>
    </li>
    <li id="wrong2"></li>
</ul>

When i clicked on Click here!, i'm supposed to get li#p2 element.

I used:

$('a.btn').click(function(e) {
    var GotIt = $(this).parents().find('li').attr('id');
});

But apparently it didn't work. I also tried closest() and also the same outcome.

How to get the element properly please?

Answer

RAUSHAN KUMAR picture RAUSHAN KUMAR · Aug 1, 2016

You should write your script as

$('a.btn').click(function(e) {
    var GotIt = $(this).closest('li').attr('id');
});

because "li" is the direct parent of your "a" element, so u can also use like

$('a.btn').click(function(e) {
    var GotIt = $(this).parent().attr('id');
});