如何测试传递给函数的元素是否是文档本身?

How do I test if the element being passed to a function is the document itself?

本文关键字:是否是 元素 文档 函数 何测试 测试      更新时间:2023-09-26

我正在编写一个小脚本,将一些代码注入到HTML元素中。

设置:

element.innerHTML = "<p>foo</p>";

除非我传递的是document本身,因为两者:

document.innerHTML

document[0].innerHTML

不能设置(至少没有显示在我的屏幕上:-)

问题:
如何测试传递给我的元素是文档本身还是正文或其他HTML元素?

您可以检查传递的对象是否与document相同:

if (element === document) {
   // ...
}

您可以通过读取[[Class]]属性来检查。

Object.prototype.toString.call( document ); // [object HTMLDocument]
Object.prototype.toString.call( document.body ); // [object HTMLBodyElement]

分别将传递的变量名传递给.call()