== Traversal ==

Traversal (Topic)

This topic contains all functions that are directly related to DOM traversal: * [[toolbox:traversal:getancestors:index|.getAncestors()]] – get a list of ancestor elements. * [[toolbox:traversal:getsiblings:index|.getSiblings()]] – get a list of siblings to the elements. * [[toolbox:traversal:getchildren:index|.getChildren()]] – get a list of children of an element. * [[toolbox:traversal:getdescendants:index|.getDescendants()]] – get a list of descendants of an element. ===== Understanding element relationships ===== The relationships of elements in a DOM tree use terminology of family relationships, with the topmost elements (starting with '''') considered "older" and the deeper nestled ones "younger" family members. For example, the following HTML snippet:
  …    
         
  …
{{ :toolbox:traversal:traversals.svg |Test}}
When starting from the third ''
  • '' element (highlit in the example above), we call: * The ''
  • '' item that we start from: **self** * The other ''
  • '' items that are on the same level as the //self// item as **siblings** * The elements that are directly underneath the //self// item, its **children** * All elements that are underneath the self item, i.e. its children and the children’s children, etc.: **descendants** * The element that is immediately one level above the self item is its **parent** * All higher-level elements, including the //parent// and up to (and including) the '''' element, are its **ancestors** The four methods in this category allow to traverse the DOM tree in either direction to find related elements.

    .getAncestors()

    The [[toolbox:traversal:getancestors:index|.getAncestors()]] method returns a list of all direct ancestor elements up to and including the '''' element. The elements are in //reverse// order, i.e. starting from the immediate //parent// element and with the '''' element as the last item in the list.

    .getSiblings()

    The [[toolbox:traversal:getsiblings:index|.getSiblings()]] method returns a list of all //sibling// elements.

    .getChildren()

    The [[toolbox:traversal:getchildren:index|.getChildren()]] method returns a list of all //immediate children// elements.

    .getDescendants()

    The [[toolbox:traversal:getdescendants:index|.getDescendants()]] method returns a list of all //descendents// of the element. This includes the children, the children’s children, and so on. ===== More information ===== * [[mdn>Web/API/Node/parentElement|Node: parentElement property]] on MDN. * [[mdn>/Web/API/Node/childNodes|Node: childNodes property]] on MDN. * [[mdn>Web/API/Node/removeChild|Node: removeChild() method]] on MDN. * [[mdn>Web/API/Element/replaceChildren|Element: replaceChildren() method]] on MDN.