12

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?

Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
Mathew Byrne
  • 3,713
  • 5
  • 25
  • 23

3 Answers3

20

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
  • 72,985
  • 14
  • 101
  • 108
4

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
  • 31,998
  • 13
  • 65
  • 69
  • 1
    `HTMLElement` as a constructor function is not defined to be accessible by any standard, and it isn't, in IE before version 8. – bobince Feb 01 '10 at 15:59
  • 1
    @bobince: HTMLElement is defined in DOM level 2. That IE7 and earlier don't support it doesn't mean it's not standardized. The reason you shouldn't use `instanceof` is because it won't work if you're doing cross-frame development. – Lèse majesté Aug 09 '12 at 00:47
  • Actually, the fact that it doesn't work cross-frame might even be an advantage in some cases: typically, foreign nodes need special treatment (i.e. importing) so they can't use the same code-path as local nodes... – Eamon Nerbonne Sep 06 '12 at 16:27
0

What about

obj instanceof HTMLElement
Wolfram Kriesing
  • 1,527
  • 10
  • 7
  • 1
    Not sure why this was ever downvoted with no explanation, but this also works and seems more reliable than a magic number. – Chris Baker Aug 29 '11 at 16:20
  • 3
    This answer is entirely redundant as Armin posted the same thing earlier, and as bobince's comment on that answer indicates, this is unreliable. My answer isn't unreliable, that "magic number" is [defined in the specification](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247). – Jim Oct 25 '11 at 21:16
  • 1
    This doesn't work in Chrome as HTMLElement is a function there – bjornl May 13 '13 at 16:21