Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery is() or has() on multiple elements

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.

like image 939
Vixed Avatar asked Feb 13 '26 02:02

Vixed


1 Answers

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>
like image 94
Zenoo Avatar answered Feb 15 '26 18:02

Zenoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!