Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/isAttached.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
* Determine if an element is attached to the DOM
* Panzoom requires this so events work properly
*/
export default function isAttached(elem: HTMLElement | SVGElement | Document) {
const doc = elem.ownerDocument
const parent = elem.parentNode
return (
doc &&
parent &&
doc.nodeType === 9 &&
parent.nodeType === 1 &&
doc.documentElement.contains(parent)
)
export default function isAttached(node: Node) {
let currentNode = node
while (currentNode && currentNode.parentNode) {
if (currentNode.parentNode === document) return true
currentNode =
currentNode.parentNode instanceof ShadowRoot
? currentNode.parentNode.host
: currentNode.parentNode
}
return false
}
24 changes: 24 additions & 0 deletions test/unit/isAttached.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,30 @@ describe('isAttached', () => {
assert(isAttached(div))
document.body.removeChild(div)
})
it('determines if an attached shadow dom element is attached', () => {
const div = document.createElement('div')
const shadowChild = document.createElement('div')
div.attachShadow({ mode: 'open' }).appendChild(shadowChild)
document.body.appendChild(div)
assert(isAttached(shadowChild))
document.body.removeChild(div)
})
it('determines if a nested, attached shadow dom element is attached', () => {
const div = document.createElement('div')
const shadowChild = document.createElement('div')
const shadowGrandChild = document.createElement('div')
shadowChild.attachShadow({ mode: 'open' }).appendChild(shadowGrandChild)
div.attachShadow({ mode: 'open' }).appendChild(shadowChild)
document.body.appendChild(div)
assert(isAttached(shadowGrandChild))
document.body.removeChild(div)
})
it('determines if a detached shadow dom element is attached', () => {
const div = document.createElement('div')
const shadowChild = document.createElement('div')
div.attachShadow({ mode: 'open' }).appendChild(shadowChild)
assert(!isAttached(shadowChild))
})
it('determines if a detached element is attached', () => {
const div = document.createElement('div')
assert(!isAttached(div))
Expand Down