jQuery:检查 jQuery 对象是否包含(包含)确切的 DOM 元素

发布于 2024-08-21 03:11:16 字数 288 浏览 3 评论 0原文

我有一个对 DOM 元素的引用,以及一个作为选择器结果的 jQuery 对象,我想检查该特定 DOM 元素是否在该 jQuery 对象中。除了循环遍历整个 jQuery 对象并检查是否相等之外,jQuery 中有没有一种简单的方法可以做到这一点?

我尝试过 .contains:contains.has:has,但它们似乎都不起作用工作。另外,我应该提到的是,我正在使用的所有元素都位于同一 DOM 树级别,因此无需担心父/子元素。

I have a reference to a DOM 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

德意的啸 2024-08-28 03:11:16
$yourJqueryObject.is(yourDomElement)

请参阅 1.6 中添加的 .is()

$yourJqueryObject.is(yourDomElement)

See .is() added in 1.6.

爱冒险 2024-08-28 03:11:16

类似于 Gumbos 答案,但更精简:

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

similar to Gumbos answer, but slimmer:

if ( obj.filter(function() { return this == el; }).length ) {
    // obj contains el
}
怂人 2024-08-28 03:11:16

试试这个:

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

elem 是您要查找的 DOM 元素。

Try this:

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

elem is the DOM element you are looking for.

∞觅青森が 2024-08-28 03:11:16

与大卫的答案类似,但更精简:

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

Similar to David's answer but even slimmer:

if ( obj.filter(el).length ) {
    // obj contains el
}
念三年u 2024-08-28 03:11:16

有点黑客,但对我有用:

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

Kinda hackish, but works for me:

$.inArray($('#single-element').get(0), $('.many-elements').get()) != -1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文