jQuery : Get first closest "parent" by type?
Asked Answered
H

4

9

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?

Halfslip answered 1/8, 2016 at 11:4 Comment(2)
Did you try closest("li") ?Carmody
Possible duplicate of Difference between jQuery parent(), parents() and closest() functionsCarmody
U
16

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');
});
Upwards answered 1/8, 2016 at 11:6 Comment(0)
R
7

Attention!

Although the given answers work in this (your) case, they are wrong - regarding the question:

"the closest parent with [what ever]"

Correct is

$element.parent().closest([what ever])

closest() includes the element itself and as long it is not [what ever], too, the script works fine, but …

This is a slumbering error in many scripts, that shows up after DOM - design changes later in development.

The docs say for closest():

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

(bold from me)

Rosabelle answered 6/9, 2019 at 16:58 Comment(0)
C
3

You can use closest(type), ie:

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

Fiddle: https://jsfiddle.net/f14vjLmc/

Carmody answered 1/8, 2016 at 11:7 Comment(0)
E
3

try this closest() JQuery Method

Excited answered 1/8, 2016 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.