views:

95

answers:

3

I am having a problem with matching elements in jQuery. Basically I have list items, and onclick I want to compare 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?

+1  A: 
var index = $('#someID > li').index( element );

index

Stefan Kendall
A: 

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');
})
Erik Philips
A: 

To compare elements try:

value === element

== is coersive comparison.

=== is explicit comparison.

To get position of an element with jQuery, read awnsers from the other people ;)

BGerrissen