Skip to content

Use different approach to check instanceof Element #95

@Joozty

Description

@Joozty

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;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions