How to find indexOf element in jQuery array?
Asked Answered
A

3

4

I have two selectors

    var allNodes = $("a.historyEntry");
    var errorNodes = $("a.historyEntry.error");

I would like to to find a node before first error node, so I need to find an index of first error node, how to do it?

I tried to use inArray method, but it doesn't work for this

$.inArray(allNodes, errorNodes.first())

or

$.inArray(allNodes, $(errorNodes.first()))

Is there any fast way to do it in jQuery or do I have to use for loop?

Acariasis answered 14/10, 2011 at 13:29 Comment(1)
If I understand you correctly: some of the nodes in allNodes have the error class, and you want to find the last "good" node before the first "error" node. Is that right?Chyle
F
10

index()?

It's like indexOf... but just without the Of... it returns the index of the element if it exists, and -1 if it doesn't.

Flagpole answered 14/10, 2011 at 13:29 Comment(0)
M
2

Use index(). It does exactly the same thing as indexOf in java.

Milone answered 14/10, 2011 at 13:34 Comment(0)
S
2

$.inArray value is the first parameter then the array:

$.inArray(allNodes, errorNodes.first())

should be:

$.inArray(errorNodes.first(), allNodes)

Example

Schism answered 14/10, 2011 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.