resize-observer-polyfill icon indicating copy to clipboard operation
resize-observer-polyfill copied to clipboard

Use different approach to check instanceof Element

Open Joozty opened this issue 3 years ago • 1 comments
trafficstars

The instanceof check does not always work correctly, especially when you work with elements created in a different contexts.

To demonstrate run this on some page:

const iframe = document.createElement('iframe')
document.body.append(iframe)

// Create element within iframe but append it to parent document
const iframeElement = iframe.contentDocument.createElement('div')
document.body.append(iframeElement)

// false because iframeElement was created in iframe context
console.log(iframeElement instanceof iframeElement.ownerDocument.defaultView.Element)

// true because element instance is checked against correct window context
console.log(iframeElement instanceof iframe.contentWindow.Element)

Suggested changes:

Stop using getWindow function and replace it with this one.

/**
 * Returns boolean indicates whether given parameter is instance of Element
 *
 * @param {Object} maybeElement
 * @returns {boolean}
 */
const isElement = maybeElement => {
    return maybeElement && 'nodeType' in maybeElement && maybeElement.nodeType === Node.ELEMENT_NODE;
};

Joozty avatar Apr 27 '22 10:04 Joozty

The same is true when using Proxies. It's enough to wrap an element in a Proxy to get this error.

tomaszcoding avatar Nov 23 '23 15:11 tomaszcoding