jQuery: get parent, parent id?

Jquery

Jquery Problem Overview


<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.

Jquery Solutions


Solution 1 - Jquery

$(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.

Solution 2 - Jquery

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

Solution 3 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpanthroView Question on Stackoverflow
Solution 1 - JqueryCasey FosterView Answer on Stackoverflow
Solution 2 - JqueryabhijitView Answer on Stackoverflow
Solution 3 - JqueryJuraj GunišView Answer on Stackoverflow