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 my
You are not storing any references to the jQuery objects, $("#div1") will return a new jQuery object containing your dom element, you are comparing two different jQuery objects containing the same dom element. inArray will work just fine if you are using the same reference in the array as when you do use the inArray method.
var arr = [],
$d1 = $("#d1"),
$d2 = $("#d2"),
$d3 = $("#d3");
arr.push($d1, $d2, $d3);
console.log(jQuery.inArray($d3, arr));
or see http://jsfiddle.net/EQQ96/2/
It's probably because each invocation of the jQuery constructor results in a new instance referring to the same DOM node. What would effectively allow you to demonstrate inArray
looks something like this:
var $div1 = $('#div1'),
$div2 = $('#div2'),
myArray = [ $div1, $div2 ];
alert(jQuery.inArray($div1,myArray));
You can't use .inArray() for object comparison by content.
I like the approach outlined here. It's very clean.
Two objects are never the same, so when you do
var object1 = $('#div1');
var object2 = $('#div1');
even if you have the same element, the objects are not the same
If you use the same object, it works
var div1 = $('#div1');
var div2 = $('#div2');
var div3 = $('#div3');
var myArray = [ div1, div2, div3 ];
jQuery.inArray( div1 , myArray); // returns 0
If you were to use purely jQuery to manipulate the jQuery Collection
then you can use the jQuery index()
method. However, the index returned is the position of the element in the dom, not the order in which it was added to the collection. If you need to deal with the order of adding then you're better of using selector strings
rather than jQuery Collection
:
var myArray = $([]).add( "#div4" ).add( "#div3" ).add( "#div1" ).add( '#div2' );
console.log( myArray.index( $('#div3') ) ); //Output: 2
JS FIDDLE DEMO
$
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.