How to check if object is a DOM 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


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


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

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

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.

Tags:

Javascript

Dom