Table of Contents

<HTMLElement>.getAncestors()

Get an array of the Element‘s ancestors, starting from the parent, up to the <html> element, optionally filtered by a callback function.

Usage:
Array = Element.getAncestors(callback = undefined)
Member of:
HTMLElement
Parameters:
callback – a Function that returns true, if an item should be added (optional ).
Returns:
An Array of HTMLElements.
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 <html> element, unless it is called on the <html> 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 <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 arrow function expression to keep the code lean.

See also

More information