2

I'm trying to detect if array of elements $a contains the element $c where:

var $a=$('#b1,#b2,#b3,#b4');
var $c=$('#b3');

but no $c.is($a) or $a.has($c) works. Looking for a jQuery answer.

Vixed
  • 3,429
  • 5
  • 37
  • 68
  • 2
    Did you try `.filter` ? `$a.filter($c).length > 0` (edit: changed to `.filter` rather than `.find` as it looks like `#b3` is not a child item (implied by the use of "contains" in the question)). – freedomn-m Jul 30 '18 at 12:48
  • Possible duplicate: https://stackoverflow.com/a/1473737/2181514 – freedomn-m Jul 30 '18 at 12:51
  • 1
    Possible duplicate of [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – freedomn-m Jul 30 '18 at 12:52
  • might not be a full solution you're after but you can do `$.inArray(needle, haystack)` – treyBake Jul 30 '18 at 12:56
  • @freedomn-m publish it as answer since is the correct one :) – Vixed Jul 30 '18 at 13:01

7 Answers7

2

You could loop through your first selector and check for all its elements individually.

Here I use jQuery .filter() method to search for the element, combined with .length to check if the element was found.

let $a=$('#b1,#b2,#b3,#b4');
let $c=$('#b3');
let $d=$('#b5');

let result = !!$a.filter((_,e) => $(e).is($c)).length;
console.log('$c in $a ? '+result);

let result2 = !!$a.filter((_,e) => $(e).is($d)).length;
console.log('$d in $a ? '+result2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b1"></div><div id="b2"></div><div id="b3"></div><div id="b4"></div>
Zenoo
  • 12,670
  • 4
  • 45
  • 69
2

You can use

$a.findIndex(x => x === $c) > -1

or you can use find in array a simple example is this

2

You can use selector property of jQuery object to check that:

var $a=$('#b1,#b2,#b3,#b4');
var $c=$('#b3');
if($a.selector.indexOf($c.selector) !== -1){
  console.log('match');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

Use inArray()

$.inArray($c,$a)
Osama
  • 2,912
  • 1
  • 12
  • 15
1

You can use this $a.findIndex(x => x === $c) > -1

0

Try

$a.findIndex(x => x === $c) > -1

to get a boolean.

If you want the elements that match use map

$a.map(x => { return x === $c })
Arno4Jackie
  • 331
  • 1
  • 20
0

You can use index for doing that:

var $a=$('#b1,#b2,#b3,#b4');
var $c=$('#b3');
if($a.index($c) > -1){
  console.log('match');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b1"></div><div id="b2"></div><div id="b3"></div><div id="b4"></div>
Ali Soltani
  • 9,589
  • 5
  • 30
  • 55