Member-only story
jQuery — Previous Elements and Attributes
jQuery is a popular JavaScript for creating dynamic web pages.
In this article, we’ll look at how to using jQuery in our web apps.
.prev()
We call the .prev()
method to get the immediately preceding sibling of each element in the set of matched elements.
If a selector is provided, it gets the precious siblings only if it matches that selector.
For example, if we have:
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
Then we get the li
that’s immediately before the li
with the class third-item
by writing:
$("li.third-item").prev().css("background-color", "red");
Then we add a red background to it.
.prevAll()
The .prevAll()
method gets all preceding siblings of each element in the set of matched elements.
For example, if we have:
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>