0

I need a XB (Cross Browser) method of detecting if an argument is a HTML Element.

Using the following code gives different results in different browsers:

Object.prototype.toString.call(element);
// returns in FF "[object HTMLDivElement]";
// returns in IE "[object Object]";

The other method I found was:

if(element.nodeType)  // true for a HTML Element;

Does someone knows a XB tested solution?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
jerone
  • 16,206
  • 4
  • 39
  • 57
  • See: http://stackoverflow.com/questions/120262/whats-the-best-way-to-detect-if-a-given-javascript-object-is-a-dom-element – Shog9 Jan 31 '10 at 22:47

1 Answers1

1

You want this:

if (element.nodeType === element.ELEMENT_NODE)
// Element.prototype.ELEMENT_NODE === 1

if (element.nodeType) is almost always true. For example, the nodeType of a comment is 8, so it would be detected as an element with your code even though it isn't.

Eli Grey
  • 35,104
  • 14
  • 75
  • 93
  • You have to compare against `1` explicitly. Although the symbolic constant `Node.ELEMENT_NODE` has been defined since the earliest DOM Level 1 Core specs, IE does not provide it. – bobince Feb 01 '10 at 16:00