tags:

views:

310

answers:

4

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?

A: 

typically you would check to see if the nodeName is defined on the object.

if(obj.nodeName){
    //Do Stuff here
}
Josh
Other DOM objects also have the nodeName property. For example, the name of an attribute is stored in nodeName too.
Jim
+1  A: 

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')

Armin Ronacher
`HTMLElement` as a constructor function is not defined to be accessible by any standard, and it isn't, in IE before version 8.
bobince
+7  A: 

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...
    }
};
Jim
Great, if it's good enough for jQuery it should be fine for my needs. Thanks!
Mathew Byrne
A: 

What about

obj instanceof HTMLElement
Wolfram Kriesing