6

The following code returns true.

console.log(document.createElement('script') instanceof Element);

Doing the same in an <iframe> context returns false:

let iframe = document.querySelector('iframe');
iframe = iframe.contentDocument || iframe.contentWindow.document;

console.log(iframe.createElement('script') instanceof Element);

Demo

Why is that?

Zenoo
  • 12,670
  • 4
  • 45
  • 69

1 Answers1

9

This is because:

1) Element is actually window.Element

2) In JS there is no such thing as a "class". Everything (almost) is an object. So instanceof checks for Prototype ancestry. When you ask is some DOM node instanceof Element you could kind of translate this to someDOMNode.prototype === Element.

3) window.Element !== document.querySelector('iframe').contentWindow.Element !!!

This will log true as expected:

console.log(iframe.createElement('script') instanceof  document.querySelector('iframe').contentWindow.Element);
Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47