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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With