循环遍历 DOM 时,如何检查我是否到达了正文元素

when looping through the DOM how do I check if I reached the body element?

本文关键字:是否 元素 正文 检查 DOM 遍历 何检查 循环      更新时间:2023-09-26

我正在通过 DOM 从链接元素循环到具有类 .ui-mobile-viewport 的最接近的元素。这可以是 DIVBODY 元素。

我需要检查它是哪个元素,但一无所获......这就是我正在尝试的:

var targetViewport;
循环将目标视口设置为 $('div.ui-mobile-viewport')

或 $('body.ui-mobile-viewport')

if ( targetViewport === $('body') ) {
   console.log("found a body");
   }

感谢您的帮助!

与其自己进行遍历,不如尝试使用 jQuery 的 .closest() 方法。所以我认为你可以这样做:

var x = $('thing-that-was-clicked').closest('.ui-mobile-viewport');
alert(x.is('body'));
alert(x.is('div'));

现在你有了.ui-mobile-viewport元素作为jQuery对象,你可以对它运行任何你想要的测试,比如检查bodydiv,如上面的代码所示。

你不能比较 jQuery 集合...你必须实际比较它们的节点,所以假设targetViewport也包含一个jQuery集合,你可以这样做。

if ( targetViewport[0] === document.body ) {
  console.log("found a body");
}

应该工作...

编辑:如果你喜欢jQuery的方式(带有额外的函数调用)

if (targetViewport.is('body')) {
  console.log("found a body");
}

您可以简单地访问元素的 nodeName。

if (targetViewport[0].nodeName.toUpperCase() === 'BODY') {
}

这样就不需要对你的检查做任何CSS查询,调用jQuery,它不依赖于任何库。

if(targetViewport[0] === document.body)
if(targetViewport[0].nodeName === 'BODY')

您正在寻找 .is() 方法,该方法检查元素是否与选择器匹配。

if (targetViewport.is('body'))