callback – a [[mdn>Web/JavaScript/Reference/Global_Objects/Function|Function]] that returns ''true'', if an item should be added (optional ).
Returns:
An [[mdn>Web/JavaScript/Reference/Global_Objects/Array|Array]] of [[mdn>Web/API/HTMLElement|HTMLElement]]s.
Notes:
* This function only returns Element nodes and ignores all other node types (like text, comments, etc.)
* The last item in the resulting Array is always the ''[[mdn>Web/HTML/Element/html|]]'' element, unless it is called on the '''' element itself, in which case this method returns an empty array.
===== Examples =====
A simple example could look like this:
document.getElementById('foo')
.getAncestors()
.forEach( (item) => {
…
});
By using a filtering function, e.g. to only collect ancestors which are ''[[mdn>Web/HTML/Element/li|
]]'' elements:
let list = document.getElementById('foo')
.getAncestors( e => e.nodeName == 'LI' );
Notes:
* The elements’ ''.nodeName'' property always contains the element name in uppercase letters!
* The above example uses an [[mdn>Web/JavaScript/Reference/Functions/Arrow_functions|arrow function expression]] to keep the code lean.
===== See also =====
* [[toolbox:traversal:getsiblings:index|.getSiblings()]]
* [[toolbox:traversal:getchildren:index|.getChildren()]]
* [[toolbox:traversal:getdescendants:index|.getDescendants()]]
===== More information =====
* [[mdn>Web/API/Node/nextSibling|Node: nextSibling property]] on MDN.