Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cross-browser and cross-frame way to check if an object is an HTML element?

Given an object obj, I would like to check if that object is a native HTML element. I could do:

if ( obj instanceof HTMLElement )

but that doesn't work across frames (e.g. on objects from an <iframe>) since each frame has its own HTMLElement constructor. Alternatively, I could just do:

if ( obj.tagName ) 

but that's not safe/reliable, as such a property could be (un)intentionally added to the object.

So, is there a reliable way to do this?

like image 585
Šime Vidas Avatar asked Nov 01 '22 09:11

Šime Vidas


1 Answers

You could use the following, accepting the fact that this will only work for UAs that support HTMLElement as a base contructor:

/// testing vars
var localBody = document.body;
var foreignBody = document.getElementById('iframe').contentDocument.body;

/// useful function
var deriveWindow = function( elm ){
    return elm && 
        elm.ownerDocument && 
        (elm.ownerDocument.defaultView || 
        elm.ownerDocument.parentWindow)
    ;
};

/// instanceofs
console.log( localBody instanceof HTMLElement );
console.log( foreignBody instanceof HTMLElement );
console.log( localBody instanceof deriveWindow(localBody).HTMLElement );
console.log( foreignBody instanceof deriveWindow(foreignBody).HTMLElement );

The output will vary from browser to browser, Firefox 25 (on Windows 7) gives:

true
true
true
true

Whereas IE 11, Opera 12, Safari 5 and Chrome 31 (on Windows 7) all give:

true
false
true
true

Fiddle:

  • http://jsfiddle.net/9sGx5/7/
  • http://jsfiddle.net/9sGx5/7/embedded/result/
like image 123
Pebbl Avatar answered Nov 09 '22 11:11

Pebbl