开发者

How to check if object is a DOM element? [duplicate]

开发者 https://www.devze.com 2023-02-06 02:08 出处:网络
This question already has answers here: How do you check if a JavaScript Object is a DOM Object? (36 answers)
This question already has answers here: How do you check if a JavaScript Object is a DOM Object? (36 answers) Closed开发者_C百科 2 years ago.

I have a function:

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

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


A DOM element implements the Element interface. So you can use:

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


Check if the nodeName property exists.

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

If you meant it literally when you said Element check for tagName property, look at the Element definition in the same spec

So to recap, do either

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

to check if it is a DOM Element or

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

to check if it is a DOM Node


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.

nodeType at MDC(docs)

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

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


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


You can use the following function

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


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

element.is("*")
0

精彩评论

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