简体   繁体   中英

Check if element is in a jquery collection

I initialize a jQuery collection like so

$collection = $([])

later on some things happend and I do a lot of

$collection = $collection.add($element)

I do this so that I can call functions like $collection.hide() on all of the elements at once.

The problem is that later I want to do something like _.contains($collection, $element) but this doesn't work. For example:

var $b = $("#content")
var $c = $([]).add(b)
console.log( _.contains($c, $b) )
console.log( _.contains($c.toArray(), $b)

Both evaluate to false.

How can I accomplish my goal with jQuery?

With .is :

if ($c.is($b)) // $c contains $b

Note that .is goes out of its way to make life easy: you can pass a selector (eg "#content" ), or an element (eg document.getElementById("content") ), or a jQuery object (eg $("#content") ) and it will work as expected in each case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM