29 lines
620 B
JavaScript
29 lines
620 B
JavaScript
|
/**
|
||
|
* Returns the parent of a node.
|
||
|
* Breaks through shadow roots.
|
||
|
* Returns null if node has no parent.
|
||
|
* @param {Node} node
|
||
|
*/
|
||
|
function getParent(node) {
|
||
|
let parent = node.parentNode
|
||
|
if (!parent) return null
|
||
|
return parent.host ? parent.host : parent
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Returns an Iterator that walks the DOM tree upwards.
|
||
|
* @param {Node} node
|
||
|
*/
|
||
|
export function createParentsIterator(node) {
|
||
|
let curNode = node
|
||
|
return {
|
||
|
next: function() {
|
||
|
curNode = getParent(curNode)
|
||
|
return curNode ? { value: curNode } : { done: true }
|
||
|
},
|
||
|
[Symbol.iterator]: function() {
|
||
|
return this
|
||
|
}
|
||
|
}
|
||
|
}
|