jQuery DOM Traversing Get previous element

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

To get the previous element you can use the .prev() method.

<ul>
    <li>Mark</li>
    <li class="anna">Anna</li>
    <li>Paul</li>
</ul>

If you are standing on the "Anna" element and you want to get the previous element, "Mark", the .prev() method will allow you to do that.

// "Mark" now has green text
$(".anna").prev().css("color", "green");

The method takes an optional selector argument, which can be used if the previous element must be a certain kind of element.

// Previous element is a "li", "Mark" now has green text
$(".anna").prev("li").css("color", "green");

If the previous element is not of the type selector then an empty set is returned, and the modifications will not do anything.

// Previous element is not a ".paul", nothing will be done in this case
$(".anna").prev(".paul").css("color", "green");


Got any jQuery Question?