Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - using inArray() to find index of jQuery object

I have a few divs that I'd like to put into an array.

When I try to use jQuery.inArray(), my div (as a jQuery object) isn't found. Why not?

var myArray = [ $("#div1"), $("#div2"), $("#div3") ];

alert(jQuery.inArray($("#div1"),myArray)); // returns -1
like image 361
ryantuck Avatar asked Jun 13 '14 21:06

ryantuck


People also ask

How do you find the index of an object in an array?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you get the index of an object inside an array that matches the condition in jQuery?

The findIndex() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable.

How do you find the index of an object in an array in TypeScript?

TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

How do you find the index of an element in an array in JS?

JavaScript Array findIndex() The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.


1 Answers

$ creates a new jQuery collection object each time, so var a = $("div"), b = $("div") will actually be two different objects that don't equal each other.

Instead you can just use the selectors or some other identifying feature of the element.

var myArray = ["#div1", "#div2", "#div3"];

However it really depends on your use case.

like image 86
Explosion Pills Avatar answered Sep 23 '22 02:09

Explosion Pills