3

Take a look at this fiddle: http://jsfiddle.net/8HHvf/
HTML

<ul id='myUL'>
    <li id="a"></li>
    <li id="b"></li>
    <li id="c"></li>
    <li id="d"></li>
    <li id="e"></li>
</ul>

JS

var arr = [];
$a=$('#a');
arr.push($a);
$a=$('#b');
arr.push($a);
$a=$('#d');
arr.push($a);
$a=$('#e');
arr.push($a);

console.log(arr);
if(jQuery.inArray($('li#b'),arr)!=-1){
    console.log('aurica!!!');
}

I am populating an array with jQuery objects but the inArray method does not find an object.
This code suppose to write "aurica!!!" but it doesn't.

do you have any idea why, and more impotent how can I find a jQuery object inside an array???

1
  • technically $('li#b') is a totally different object from any saved variable you put in the array. Commented Jun 15, 2014 at 15:18

4 Answers 4

2

By reassigning $a, you're just writing $('#e') to your array four times. You can see this if you:

console.log(JSON.stringify(arr))

in a modern browser.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to push HTMLElement if you want to check for equality or want to compare as jQuery objects are always unique.

$(document) != $(document);

You can simplify your code to:

var arr = $('#a,#b,#c,#d').get();
console.log(arr);
if (jQuery.inArray($('li#b').get(), arr) != -1) {
    console.log('aurica!!!');
}

.get() converts jQuery object to HTMLElement which can be compared upon.

Comments

0

i think the problem are the .val() attribute missing in the if condition. Try with this, I hope it can help you

var arr = [];
var a=$('#a').val();
arr.push(a);
a=$('#b').val();
arr.push(a);
a=$('#d').val();
arr.push(a);
a=$('#e').val();
arr.push(a);

console.log(arr);
if(jQuery.inArray($('li#b').val(),arr)!=-1){
   console.log('aurica!!!');
}
arr = jQuery.grep(arr, function(value) {
  return !$('#b').is(value);;
});
console.log(arr);

Comments

0

By pushing the return value of the selector, you are creating a new array and storing it into your array variable. To be able to compare it at a late point of time, you should actually be storing the element itself of anything from it that is (uniquely) comparable.

Below changes to your JS should do the trick,

$(function() {
var arr = [];
$a=$('#a');
arr.push($a[0]);
$a=$('#b');
arr.push($a[0]);
$a=$('#d');
arr.push($a[0]);
$a=$('#e');
arr.push($a[0]);

console.log(arr);
if(jQuery.inArray($('li#a')[0],arr)!=-1){
    console.log('aurica!!!');
}
arr = jQuery.grep(arr, function(value) {
  return !$('#b').is(value);;
});
console.log(arr);

//alert(y);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.