Javascript 如何检查对象是否为 DOM 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4754088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:55:30  来源:igfitidea点击:

How to check if object is a DOM element?

javascriptdom

提问by BrunoLM

I have a function:

我有一个功能:

function Check(o)
{
    alert(/* o is a DOM element ? "true" : "false" */);
}

How can I check if the parameter ois a DOM object or not?

如何检查参数o是否为 DOM 对象?

回答by David Hellsing

A DOM element implements the Elementinterface. So you can use:

DOM 元素实现该Element接口。所以你可以使用:

function Check(o) {
    alert(o instanceof Element);
}

回答by Martin Jespersen

Check if the nodeNameproperty exists.

检查该nodeName属性是否存在。

Basically check if it is a Node: look at the DOM lvl 1 specs, check the Node definition.

基本上检查它是否是Node:查看DOM lvl 1 规范,检查节点定义。

If you meant it literally when you said Elementcheck for tagNameproperty, look at the Element definition in the same spec

如果您说Element检查tagName属性时是字面意思,请查看同一规范中的 Element 定义

So to recap, do either

所以回顾一下,要么做

function Check(o)
{
    alert(o.tagName ? "true" : "false");
}

to check if it is a DOM Element or

检查它是否是 DOM 元素或

function Check(o)
{
    alert(o.nodeName ? "true" : "false" );
}

to check if it is a DOM Node

检查它是否是一个 DOM 节点

回答by user113716

Instead of just checking for the existence of a property, I'd check its specific value.

我不只是检查属性是否存在,而是检查其特定值。

This assumes you're looking for a "type 1" element.

这假设您正在寻找“类型 1”元素。

nodeType at MDC(docs)

nodeType at MDC(文档)

function Check(o) {
    alert( o && o.nodeType && o.nodeType === 1 );
}

You could still get an object that has the nodeTypeproperty that isn't actually a DOM node, but it would also have to have a matching value of 1to give a false positive.

您仍然可以获得一个对象,该对象具有nodeType实际上不是 DOM 节点的属性,但它也必须具有匹配的值1才能给出误报。

回答by K-Gun

Late answer, but a document fragment could be a node as well:

迟到的答案,但文档片段也可以是一个节点:

function isNode(node) {
    return node && (node.nodeType === 1 || node.nodeType == 11);
}

Credits: https://github.com/k-gun/so/blob/4.8.1/so.dom.js#L50

学分:https: //github.com/k-gun/so/blob/4.8.1/so.dom.js#L50

回答by zhy2002

You can check if a DOM node is element with JQuery:

您可以使用 JQuery 检查 DOM 节点是否为元素:

element.is("*")

回答by Ben Rowe

You can use the following function

您可以使用以下功能

function isNode(o)
{
  return o && 'nodeType' in o;
}