Reputation: 335
I have a problem retrieving an ID of a "li" element which I would use in AJAX.
<div id="subTab">
<ul class="nav nav-pills" style="display:none" id="users">
<li id="AUser"><a href="#AUser"><span class="glyphicon glyphicon-user"></span> User Management</a></li>
<li id="ARole"><a href="#ARole">Role Management</a></li>
</ul>
</div>
With ajax using this code I add "active" class to the "li" element:
$(this).closest('ul li').addClass('active');
So my question is, how to retrieve the ID attribute of li that would have the active class in it? I tried lots of ways, but none of them were successful..
$('#subTab').find('li .active').attr('id');
this one returns nothing.
$('#subTab').find('ul li').closest('.active').attr('id');
this one returns the "ul" elements id..
If anyone has a solution, please help me solve this, Thank you for your time.
Upvotes: 0
Views: 96
Reputation: 4143
The short way:
$('#subTab li.active').attr('id')
In action: jsfiddle
Upvotes: 2
Reputation: 707
use .each because 'active' class apply to more than one li.
$("#subTab").find('ul li').addClass('active');
$("#subTab").find('li.active').each(function(){
console.log($(this).attr('id'));
});
Upvotes: 0
Reputation: 64536
The issue is a space in the selector. A space is used for selecting descendants, what you're asking for is to find an element with class active
that is a descendant of an li
.
Remove the space:
$('#subTab').find('li.active').attr('id');
Now it's asking for elements that are a <li>
and have class active
.
From W3C docs:
A descendant selector is made up of two or more selectors separated by white space. A descendant selector of the form "A B" matches when an element B is an arbitrary descendant of some ancestor element A
Upvotes: 1
Reputation: 38112
You don't need the space here. When you're using space, the selector will match the descendants with class active
of your li
elements instead:
$('#subTab').find('li.active').attr('id');
Upvotes: 2