3

The following code work in FF but not IE8:

var j = "test";
alert(j instanceof HTMLElement);

I don't think IE uses the HTMLElement object. Is there a safe way to do this check in IE? Perhaps there is a YUI solution?

stevebot
  • 23,275
  • 29
  • 119
  • 181
  • possible duplicate of [Javascript isDOM -- How do you check if a Javascript Object is a DOM Object?](http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object) – Roatin Marth Apr 21 '11 at 18:11
  • @Roatin nope, an element can be in the DOM without being an HTML element. – stevebot Apr 21 '11 at 18:17

2 Answers2

9

I use to check the nodeType property, it should be 1 for all HTML element objects.

I used it in my crossbrowser library before I switched to jQuery.

text has a nodeType of 3 and any custom objects probably won't have a nodeType property at all.

David Mårtensson
  • 7,550
  • 4
  • 31
  • 47
  • http://help.dottoro.com/ljkadgoo.php I think you got it backwards? Text is type 3, and Element is type 1? – stevebot Apr 21 '11 at 19:58
  • Someone needs to correct this answer, it is backwards :) text node: 3, element node: 1, comment node: 8, etc etc. See https://developer.mozilla.org/en/nodeType – npup Aug 16 '11 at 17:00
  • Fixed the numbers, sorry for getting them backwards and not noticing the first comment notice emails :/ – David Mårtensson Aug 17 '11 at 09:22
2

If you look at the jQuery source code (not the minified one ffs!), you'll see they make use of nodeType a lot.

Christian
  • 27,509
  • 17
  • 111
  • 155