Re: isElement - determining if an object is an element



On Jul 31, 1:28 am, RobG <rg...@xxxxxxxxxxxx> wrote:
On Jul 31, 2:33 pm, kangax <kan...@xxxxxxxxx> wrote:
[...]



It could be rewritten like so:

var isElement = (function(){
  var el = document.createElement('div'), fn;
  if (el instanceof Element) {

That causes IE8 Beta 1 to barf with "Element is not defined".
Modifying it to:

  if (Element && (el instanceof Element))

or

  if (Element) {
    if (...) {

gets the same result, it wants a more explicit test:

  if (typeof Element != 'undefined' && (...))

Perhaps that's documented on one of the IE8 blogs somewhere...

Interesting. Should one really care about such quirks while a browser
is in its early development state?


    fn = function(o) {
      return o instanceof Element;
    }
  }
  else {
    fn = function(o) {
      return o && typeof 'nodeType' in o && o.nodeType === 1;

After applying your fix to the above to remove typeof, what is the
point of the test?  Its use as a guard here seems unnecessary: if o
doesn't have a nodeType property, o.nodeType will return undefined and

I wrongly assumed that `in` doesn't call `GetValue` and so is safer to
use with host objects.

the test fails (even in IE8b).

    }
  }
  el = null;
  return fn;

})();

We don't perform such branching in prototype.js to avoid
inconsistencies across browsers.

isElement(document.createElement('div')); // true in IE and FF
isElement({ nodeType: 1 }); // true in IE, but false in FF

But there you have an inconsitency, lending support to the argument
that feature detection is much better than inference (i.e. if you
expect an object to have a particular property, test for that
property, don't test it for some other property to infer that is has
the one you really want).


It certainly makes sense to test for a particular property rather than
relying on some generalized helper. It appears, though, that the need
for "isElement" exists. The goal is to implement its behavior in a
most intuitive and generalized way.

--
kangax
.



Relevant Pages