jQuery prev() Method - CodingTag
×


jQuery prev()

1447

  • This jQuery method is used to fetch the previous sibling element of the selected HTML element.
  • Siblings: siblings are the elements which has the same parents as selected element.

  • If we talk about the DOM traversal tree, this method traverses backward along the previous sibling of the DOM tree nodes.
  • To traverse the only the forward DOM elements or next siblings of the selected element, use next() jQuery method.
  • To traverse both forward and backward DOM elements or siblings of the selected element, use siblings() jQuery method.
  • To return the all previous siblings of the selected HTML element, use prevAll() jQuery function.
  • To return the all previous siblings of the selected HTML element between given range, use prevUntil() jQuery method.

Related Topics:

jQuery nextAll
jQuery nextUntil

jQuery prev

Syntax:

$(selector).prev(filter) ;

Parameter description:

  • filter: This parameter is used to narrow down the search for previous sibling element. It can be an expression, element or jQuery object. It is optional.

Example:

In this example we highlight the previous sibling element of <div> element.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
padding:10px;
margin:10px;
font-size:20px;
}
h3{
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").prev().css("border","3px solid green");
});
});
</script>
</head>
<body>

<h2> jQuery prev() method Example </h2>
<h3> This heading is the previous sibling of div tag </h3>
<div>
<h3> This is heading of div element </h3>
</div>
<h3> This heading is the next sibling of div tag </h3>
<h3> This heading is also the next sibling of div tag </h3>
<h3 class="stop"> This heading is also the next sibling of div tag with class stop </h3>
<button> Click Me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments