I have the following jQuery and I'm confused as to why it's returning -1
and not 0 ? Is anyone able to explain:
var one = $('.test');
var two = $('.test2');
var myArray = [];
myArray.push(one);
if($.inArray($('.test'), myArray) < 0) {
myArray.push(two);
}
console.log($.inArray($('.test'), myArray)); //return -1
I setup http://jsfiddle.net/ecrMw/1/ and I'm trying to return 0
for $('.test')
? That is, find it in the array ?
Because the jQuery object is actually a collection not a DOM element. What you're looking for is the facsimile of:
var one = $('.test')[0];
var two = $('.test2')[0];
// on with your code
Then you'd test again against the element:
if ($.inArray($('.test')[0], myArray)){
}
otherwise (notated bluntly) you're adding arrays to an array:
var one = $('.test'); // actually a [$] array
var two = $('.test2'); // actually another [$] array
var myArray = []; // empty array
myArray.push(one); // one = [[$]];
Then comparing if an array is within another array becomes a more complex issue.
[0]
but that doesn't search across everything in the array - Andy 2012-04-04 18:34
[$]
to myArray
which can contain multiple classes i.e. [$('.test'), $('.test12')]. Then all I'm basically trying to do - if the element is already in the array, ignore otherwise add - Andy 2012-04-04 18:42
var classes = []; classes.push('test1'); if (!$.inArray('test2',classes)){ classes.push('test2'); }
then you can turn it in to a query (either as an "AND" ($('.'+classes.join('.'))
) or "OR" ($('.'+classes.join(',.'))
) type match - Brad Christie 2012-04-04 18:49
var one = $('.test');
console.log($('.test') == one); //Outputs false
Javascript does not know how to compare the two objects therefore their comparison returns false. I am guessing that its looking at the memory address to determine their equality.
Since js cannot determine their equality, I'm guessing the jquery library does not handle objects in the inArray() method.
Check this fiddle ,I have re-wrote it
e.g
var found = $('.test,.test2').map(function(){return $(this).get(0)})
var foundAry=$.makeArray(found);
console.log($.inArray($('.test').get(0), foundAry));
The point is that you need to search for DOM object in array not for JQUERY object in array.
hope this will help you.
Why use an array? You could use a jQuery collection.
var $one = $('.test'),
$two = $('.test2'),
$myCollection = $();
$.merge( $myCollection, $one );
if( $myCollection.index( $one ) < 0) {
$.merge( $myCollection, $two );
}
console.log( $myCollection.index( $one ) ); //returns 0
console.log($.inArray(one, myArray));
which does return 0 - j08691 2012-04-04 18:32