Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to detect if a given Javascript object is a DOM Element? [duplicate]

Say for instance I was writing a function that was designed to accept multiple argument types:

var overloaded = function (arg) {
    if (is_dom_element(arg)) {
        // Code for DOM Element argument...
    }
};

What's the best way to implement is_dom_element so that it works in a cross-browser, fairly accurate way?

like image 931
Mathew Byrne Avatar asked Sep 23 '08 10:09

Mathew Byrne


People also ask

Is DOM JavaScript object?

The HTML DOM is a standard object model and programming interface for HTML. It defines: The HTML elements as objects.

What is nodeType in JavaScript?

Definition and Usage. The nodeType property returns the node type, as a number, of the specified node. If the node is an element node, the nodeType property will return 1. If the node is an attribute node, the nodeType property will return 2. If the node is a text node, the nodeType property will return 3.


2 Answers

jQuery checks the nodeType property. So you would have:

var overloaded = function (arg) {
    if (arg.nodeType) {
        // Code for DOM Element argument...
    }
};

Although this would detect all DOM objects, not just elements. If you want elements alone, that would be:

var overloaded = function (arg) {
    if (arg.nodeType && arg.nodeType == 1) {
        // Code for DOM Element argument...
    }
};
like image 56
Jim Avatar answered Oct 30 '22 20:10

Jim


Probably this one here:

node instanceof HTMLElement

That should work in most browsers. Otherwise you have to duck-type it (eg. typeof x.nodeType != 'undefined')

like image 22
Armin Ronacher Avatar answered Oct 30 '22 20:10

Armin Ronacher