Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery : Get first closest "parent" by type?

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?

like image 517
夏期劇場 Avatar asked Dec 06 '22 17:12

夏期劇場


1 Answers

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');
});
like image 85
RAUSHAN KUMAR Avatar answered Jan 03 '23 07:01

RAUSHAN KUMAR