93
<ul id ="myList">
<li><a href="www.example.com">link</a></li>
</ul>

How can I get the id of the ul (myList) using jQuery? My j-script event is triggered when the a link is clicked. I have tried:

$(this).parent().attr('id');

But it gets the id of the li, I need to go one higher, and I cant attach the click to the li either.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
panthro
  • 22,779
  • 66
  • 183
  • 324
  • Does this answer your question? [Finding the id of a parent div using Jquery](https://stackoverflow.com/questions/545978/finding-the-id-of-a-parent-div-using-jquery) – TylerH Nov 22 '22 at 14:28

3 Answers3

192
$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

Casey Foster
  • 5,982
  • 2
  • 27
  • 27
  • 1
    calling parent. twice is neither efficient not future proof – gotofritz Apr 21 '12 at 16:40
  • 2
    `parent().parent()` is definitely faster than `parents('ul')` as the latter will search all the way up to the tag looking for
      tags and return all of them. `closest('ul')` is a good choice because it stops searching after the first occurrence, but closest also includes the element it is being called on. Perhaps `$(this).parent().closest('ul')` is the best choice, unless the `$(this)` will never be a
        .
    – Casey Foster Apr 21 '12 at 18:55
  • 1
    Agreed that 'closest' is the ideal approach. Did not realize it at first, but any selector can work in place of 'ul'. – HoldOffHunger Nov 01 '16 at 14:55
14
 $(this).closest('ul').attr('id');
abhijit
  • 1,958
  • 3
  • 28
  • 39
2

Here are 3 examples:

$(document).on('click', 'ul li a', function (e) {
    e.preventDefault();

    var example1 = $(this).parents('ul:first').attr('id');
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');

    var example2 = $(this).parents('ul:eq(0)').attr('id');
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');
  
    var example3 = $(this).closest('ul').attr('id');
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id ="myList">
  <li><a href="www.example.com">Click here</a></li>
</ul>

<div id="results">
  <h1>Results:</h1>
</div>

Let me know whether it was helpful.