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 this object is a native HTML element. I could do:

if ( obj instanceof HTMLElement )

but this does not work through frames (for example, on objects from <iframe>), since each frame has its own constructor HTMLElement. Alternatively, I could just do:

if ( obj.tagName ) 

but it is not safe / reliable, since this property can be (un) intentionally added to the object.

So, is there a reliable way to do this?

+4
source share
4 answers

, , UA, HTMLElement :

/// 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 );

, Firefox 25 ( Windows 7) :

true
true
true
true

IE 11, Opera 12, Safari 5 Chrome 31 ( Windows 7) :

true
false
true
true

:

+2

, toString .

HTMLElement :

  • [object HTML
  • Element]

:

var str = Object.prototype.toString.call(obj),
    isHtmlElement = str.indexOf('[object HTML') === 0 
                 && str.indexOf('Element]') > -1;

( ) .

0

nodeType nodeName, , , , HTML.

http://www.w3schools.com/dom/dom_nodetype.asp

//Returns true if it is a DOM element    
function isElement(o){
    if (typeof o === "object" && o.nodeType === 1 && typeof o.nodeName==="string") {
        return true;
    } 
    return false;    
 }
0

What about function isPrototypeOf? HTMLElement.prototype.isPrototypeOf(obj)should return truefor any HTML element, but falsefor some random object.

I did not have the opportunity to test it through frames, so my only problem would be if she faced the same problem as instanceOf.,.

0
source

All Articles