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.
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.
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>
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>
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 })
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>