I'm trying to get a location of an element in a jQuery set.
Here's what I tried so far.
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
I'm trying to get a location of an element in a jQuery set.
Here's what I tried so far.
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
4 Answers
Reset to default 11if 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'));
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);
Live DEMO
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);
Live DEMO
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
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') );
})
a
element) – tobyodavies Commented May 2, 2012 at 1:20