JQuery: Get the parent element id of a clicked element

20,463

instead of using closest you can use parent like this...

var id = $(this).parent().attr("id");

Notice you can use the this keyword to reference the element that kicked off the event. As you have it, you are using the value of buttonID as the element selector which would have a value of "popupDivClose" and without adding a # at the start it will not search for an ID, but rather a tag element called "popupDivClose".

If you wanted to keep using buttonID you could have used this line of code to get it working...

var id = $("#" + buttonID).parent().attr("id");

However, I would have preferred to write the whole event like so...

$(".popupCloseClass").click(function (event) {
    event.preventDefault();

    var id = $(this).parent().attr("id");

    disablePopup(id);
});

notice the use of event.preventDefault(); this will ensure that the browser will not process the natural action for a link click (i.e. page navigation) - though, in Chrome at least, you need to specify a href value for the navigation anyway

Here is a working example

Share:
20,463
Y2theZ
Author by

Y2theZ

Updated on July 21, 2022

Comments

  • Y2theZ
    Y2theZ almost 2 years

    I have a div like this:

    <div id="popupDiv1" class="popupDivClass">
        <a id="popupDivClose" class="popupCloseClass">x</a>
    </div>
    

    When I click on the 'x' (I want to run a jquery function called disablePopup(id); where id is the id of the coresponding popupDiv (I have many popupDiv each with it's own X button.

    in order to do so I implemented the following

    $(".popupCloseClass").click(function (event) {
        var buttonID = $(event.target).attr("id");
        var id = $( buttonID).closest("div").attr("id");
    disablePopup(id);
    });
    

    basicaly I get the id of the popupCloseClass clicked then I get the id of it's parent (the corresponding popupDiv) via the closest method. then I call disablePopup.

    But this is not working.

    I even tryed to use the var buttonID = $(buttonID).parent().attr("id"); method but did not work either.

    I also tried var id = this.id;

    Any help is greatly appreciated

    Thanks

  • musefan
    musefan about 12 years
    Note that parent() will only return the immediate parent and therefore the selector parameter is pointless. you can however use parents(selector) which will take a selector and return all parents (all the way up the tree) that match the selector
  • Nicola Peluchetti
    Nicola Peluchetti about 12 years
    @musefan yes it pointless, in my experience it's better to use closest() because you usually end up modifying your html and breaking the code that uses parent()
  • musefan
    musefan about 12 years
    A good point to make, definitely something for consideration. However, I am yet to have broken my code this way... then again, I don't use this kind of functionality too often anyway