previous
previous(element[, cssRule][, index = 0]) -> HTMLElement | undefined
Returns element
's previous sibling (or the index'th one, if index
is specified) that matches cssRule
. If no cssRule
is provided, all previous siblings are considered. If no previous sibling matches these criteria, undefined
is returned.
The Element.previous
method is part of Prototype's ultimate DOM traversal toolkit (check out Element.up
, Element.down
and Element.next
for some more Prototypish niceness). It allows precise index-based and/or CSS rule-based selection of any of element
's previous siblings. (Note that two elements are considered siblings if they have the same parent, so for example, the head
and body
elements are siblings—their parent is the html
element.)
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 previous sibling is returned (this is similar as calling previousSibling
except Element.previous
returns an already extended element).
If an index is passed, element
's corresponding previous sibling is returned. (This is equivalent to selecting an element from the array of elements returned by the method previousSiblings()
). Note that the sibling right above element
has an index of 0.
If cssRule
is defined, Element.previous
will return the element
first previous sibling that matches it.
If both cssRule
and index
are defined, Element.previous
will collect all of element
's previous siblings matching the given CSS rule and will return the one specified by the index.
In all of the above cases, if no previous sibling is found, undefined
will be returned.
Examples
<ul id="fruits">
<li id="apples">
<h3>Apples</h3>
<ul id="list-of-apples">
<li id="golden-delicious" class="yummy">Golden Delicious</li>
<li id="mutsu" class="yummy">Mutsu</li>
<li id="mcintosh">McIntosh</li>
<li id="ida-red">Ida Red</li>
</ul>
<p id="saying">An apple a day keeps the doctor away.</p>
</li>
</ul>
$('saying').previous();
// equivalent:
$('saying').previous(0);
// -> ul#list-of-apples
$('saying').previous(1);
// -> h3
$('saying').previous('h3');
// -> h3
$('ida-red').previous('.yummy');
// -> li#mutsu
$('ida-red').previous('.yummy', 1);
// -> li#golden-delicious
$('ida-red').previous(5);
// -> undefined