Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use different approach to check instanceof Element #95

Open
Joozty opened this issue Apr 27, 2022 · 1 comment
Open

Use different approach to check instanceof Element #95

Joozty opened this issue Apr 27, 2022 · 1 comment

Comments

@Joozty
Copy link

Joozty commented Apr 27, 2022

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;
};
@tomaszcoding
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants