up

up(element, [cssRule][, index = 0]) -> HTMLElement | undefined

Returns element’s first ancestor (or the index’th ancestor, if index is specified) that matches cssRule. If no cssRule is provided, all ancestors are considered. If no ancestor matches these criteria, undefined is returned.

The Element.up method is part of Prototype’s ultimate DOM traversal toolkit (check out Element.down, Element.next and Element.previous for some more Prototypish niceness). It allows precise index-based and/or CSS rule-based selection of any of element’s ancestors.

As it totally ignores text nodes (it only returns elements), you don’t have to worry about whitespace-only nodes.

And as an added bonus, all elements returned are already extended allowing chaining:


$(element).down(1).next('li', 2).hide();

Walking the DOM has never been that easy!

Arguments

If no argument is passed, element’s first ancestor is returned (this is similar as calling parentNode except Element.up returns an already extended element.

If an index is passed, element’s corresponding ancestor is is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.ancestors). Note that the first element has an index of 0.

If cssRule is defined, Element.up will return the first ancestor that matches it.

If both cssRule and index are defined, Element.up will collect all the ancestors matching the given CSS rule and will return the one specified by the index.

In all of the above cases, if no descendant is found, undefined will be returned.

Examples


<html>
  […]
  <body>
    <ul id="fruits">
      <li id="apples" class="keeps-the-doctor-away">
        <ul>
          <li id="golden-delicious">Golden Delicious</li>
          <li id="mutsu" class="yummy">Mutsu</li>
          <li id="mcintosh" class="yummy">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
      </li>
    </ul>
  </body>
</html>


$('fruits').up();
// equivalent:
$('fruits').up(0);
// -> body

$('mutsu').up(2);
// -> ul#fruits

$('mutsu').up('li');
// -> li#apples

$('mutsu').up('.keeps-the-doctor-away');
// -> li#apples

$('mutsu').up('ul', 1);
// -> ul#fruits

$('mutsu').up('div');
// -> undefined