Reputation: 35274
I'm trying to get a location of an element in a jQuery set.
I want to be able to do something like this:
$('ul').find('a').indexOf('.active');
And get the location of the .active
in the set of a
's.
Is there something like an indexOf()
function for jQuery? The index()
method doesn't work
Upvotes: 10
Views: 21989
Reputation: 7297
Your logic is sound, you're just grabbing the wrong element: http://jsfiddle.net/xz9dW/19/
var index = $('ul a.active').closest('li').index();
The a
link has no index()
value since it has no siblings; you have to grab the li
Upvotes: 0
Reputation: 150253
You just need to give the index
function a jQuery object:
var elements = $('ul a');
var index = elements.index(elements.filter('.active')); // 2
alert(index);
There is no such function out of the box, it can be done easily like this:
var index = -1;
$('ul a').each(function(i){
if ($(this).hasClass('active')){
index = i;
return false;
}
});
alert(index);
Upvotes: 0
Reputation: 28099
if you pass a jQuery set ($searchFor
) as an argument to the index
method of another jQuery set ($searchIn
) i.e.
$searchIn.index($searchFor)
it will return the index of $searchFor
in the set $searchIn
In your example:
$('ul a').index($('ul a.active'));
Upvotes: 11
Reputation: 13233
You can do this by just asking for it in the selector:
$('ul a.active')
What do you mean by getting the location however? Do you mean position? or URL?
If you would like to know which one you click
on lets say.. You would use $(this)
inside your event function. Here is an example which returns the current position of the element you click on, if there are multiple with the .active
class:
To get the position:
$('ul a.active').click(function(){
alert( $(this).position() );
})
To get the URL location:
$('ul a.active').click(function(){
alert( $(this).attr('href') );
})
Upvotes: -2