I am having a problem with matching elements in jQuery.
Basically I have list items, and onclick
I want to pare two elements to find out its position within the list, ie.
<ul id="someID">
<li>something</li>
<li>something</li>
<li>something</li>
</ul>
// here is the script
var row = 0,
element = $('#someID > li:eq(1)').get(0);
$('#someID > li').each(function(index, value) {
if (value == element) {
row = index;
return false;
}
}
element
is in the proper scope and this all should work (or so I think). The only reason I can see that it might not work is that the browser sees each list-item
as the same, because its innerHTML
is the same and has no id
or class
.
Is there some other way that I can get the position of a list-item within a list?
I am having a problem with matching elements in jQuery.
Basically I have list items, and onclick
I want to pare two elements to find out its position within the list, ie.
<ul id="someID">
<li>something</li>
<li>something</li>
<li>something</li>
</ul>
// here is the script
var row = 0,
element = $('#someID > li:eq(1)').get(0);
$('#someID > li').each(function(index, value) {
if (value == element) {
row = index;
return false;
}
}
element
is in the proper scope and this all should work (or so I think). The only reason I can see that it might not work is that the browser sees each list-item
as the same, because its innerHTML
is the same and has no id
or class
.
Is there some other way that I can get the position of a list-item within a list?
Share Improve this question asked Aug 17, 2010 at 20:48 TomTom 7,0917 gold badges49 silver badges80 bronze badges 2- 1 Your code works for me as long as you add the closing parenthesis that you're missing. Try it: jsfiddle/83hcP – user113716 Commented Aug 17, 2010 at 20:54
- Well its a good thing I found out about index(), that nice. But it turns out that that wasn't actually my problem, it was the #someID. This was my code simplified, and I was not getting the correct element to loop through. – Tom Commented Aug 17, 2010 at 20:59
4 Answers
Reset to default 4var index = $('#someID > li').index( element );
index
To pare elements try:
value === element
== is coersive parison.
=== is explicit parison.
To get position of an element with jQuery, read awnsers from the other people ;)
For the record, now there is the "is()" function:
element.is(value)
If for some reason $.index() does not work for you...
Any reason you can't add an attribute or class to the object then loop through the list of items to find it?
$('li').click(function()
{
$(this).addClass('Selected');
.. loop through element to find index
.HasClass('Selected');
$(this).removeClass('Selected');
})