jqueryHow can I use jQuery prev() to access the previous element in a selection?
The jQuery prev()
method can be used to access the previous element in a selection. This method will traverse the DOM tree to find the previous sibling of the selected element.
Example code
<div>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
</div>
<script>
$( "p:last" ).prev().css( "background-color", "red" );
</script>
Output example
<div>
<p>This is the first paragraph.</p>
<p style="background-color: red;">This is the second paragraph.</p>
<p>This is the third paragraph.</p>
</div>
The code above will select the last <p>
element in the selection, then use the prev()
method to select the previous <p>
element. The css()
method is then used to set the background color of the element to red.
Code explanation
$( "p:last" )
- This will select the last<p>
element in the selection.prev()
- This will traverse the DOM tree to find the previous sibling of the selected element.css( "background-color", "red" )
- This will set the background color of the element to red.
Helpful links
More of Jquery
- How do I use jQuery ZTree to create a hierarchical tree structure?
- How can I get the y position of an element using jQuery?
- How do I use jQuery to detect window resize events?
- How do I use jQuery to zip files?
- How do I create a jQuery Yes/No dialog?
- How do I prevent XSS attacks when using jQuery?
- How can I use jQuery to check if an element is visible?
- How do I use jQuery Select2 to select multiple options?
- How do I use jQuery to validate an email address?
- How do I use jQuery to trigger an event?
See more codes...