开发者

jQuery: Check if jQuery object contains (includes) exact DOM element

开发者 https://www.devze.com 2022-12-19 05:33 出处:网络
I have a reference to a DOM 开发者_Go百科element, and a jQuery object which is the result of a selector, and I want to check if that specific DOM element is in that jQuery object. Short of looping thr

I have a reference to a DOM 开发者_Go百科element, and a jQuery object which is the result of a selector, and I want to check if that specific DOM element is in that jQuery object. Short of looping through the whole jQuery object and checking for equality, is there a straightforward way in jQuery to do this?

I have tried .contains, :contains, .has and :has, and none of them seem to do the job. Also, I should mention that all the elements I'm working with are on the same DOM tree level, so there is no need to worry about parents/children.


$yourJqueryObject.is(yourDomElement)

See .is() added in 1.6.


similar to Gumbos answer, but slimmer:

if ( obj.filter(function() { return this == el; }).length ) {
    // obj contains el
}


Try this:

var result = $("selector").find("*").filter(function() {
    return this === elem;
}).length === 1;

elem is the DOM element you are looking for.


Similar to David's answer but even slimmer:

if ( obj.filter(el).length ) {
    // obj contains el
}


Kinda hackish, but works for me:

$.inArray($('#single-element').get(0), $('.many-elements').get()) != -1
0

精彩评论

暂无评论...
验证码 换一张
取 消