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 do I use the jQuery masked input plugin?
- How do I download a zip file using jQuery?
- How do I use jQuery to change the z-index of an element?
- How do I use jQuery to set query parameters?
- How do I use jQuery to zip files?
- How can I use JQuery with Yii2?
- How can I use jQuery and React together in my software development project?
- How do I use a jQuery queue?
- How do I use the jQuery prop() method?
See more codes...