Search and get the postion of an element in jquery

index() is used for search for a given element from among the matched elements.

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

If a selector string is passed as an argument, .index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector. If the element is not found, .index() will return -1.

Eg:
<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
var listItem = document.getElementById( "bar" );
console.log( "Index: " + $( "li" ).index( listItem ) );
We get back the zero-based position of the list item:

Index: 1

Sample code and demo is here

Demo

No comments:

Post a Comment