NibblyPig
NibblyPig

Reputation: 52962

How can I identify which li in a ul has a particular class?

I have a standard <ul> with some <li>

One of the <li> has the class 'porcupine'

how can I work out the index of the li with that class?

Upvotes: 1

Views: 726

Answers (4)

Mutation Person
Mutation Person

Reputation: 30530

You want index()

See it working at: http://jsfiddle.net/4ZncT/1/

alert($("ul>li.porcupine").index());

Upvotes: 0

user53791
user53791

Reputation:

Or if you already have a reference to the object then

jQueryElement.find('li.porcupine:first').index() where jQueryElement is the jQuery wrapper around the ul or if not

$(htmlDomElement).find('li.porcupine:first).index()

you can remove first if you want more to match more than one

Upvotes: 0

SLaks
SLaks

Reputation: 888293

Like this:

$('ul.Something li.porcupine').index()

Upvotes: 6

hunter
hunter

Reputation: 63562

You can call the index() method

$("li.porcupine").index();

http://api.jquery.com/index/

Return Values

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 original element relative to the elements matched by the selector. If the element is not found, .index() will return -1.

Upvotes: 2

Related Questions