instance method Element#up

View source on GitHub →

Element#up([expression[, index = 0]]) → Element
Element#up([index = 0]) → Element
  • expression (String) – A CSS selector.

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

More information

The Element.up method is part of Prototype's ultimate DOM traversal toolkit (check out Element.down, 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 nodes.

And as an added bonus, all elements returned are already extended (see Element.extended) allowing chaining:

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

Walking the DOM has never been that easy!


If no arguments are passed, element's first ancestor is returned (this is similar to calling parentNode except Element.up returns an already extended element.

If index is defined, element's corresponding ancestor 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 expression is defined, Element.up will return the first ancestor that matches it.

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

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


    <ul id="fruits">
      <li id="apples" class="keeps-the-doctor-away">
          <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>

Get the first ancestor of "#fruites":

// or:
// -> body

Get the third ancestor of "#mutsu":

// -> ul#fruits

Get the first ancestor of "#mutsu" with the node name "li":

// -> li#apples

Get the first ancestor of "#mutsu" with the class name "keeps-the-doctor-away":

// -> li#apples

Get the second ancestor of "#mutsu" with the node name "ul":

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

Try to get the first ancestor of "#mutsu" with the node name "div":

// -> undefined

This method can be called either as an instance method or as a generic method. If calling as a generic, pass the instance in as the first argument.