jQuery siblings()
×


jQuery siblings()

0 584

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

  • If we talk about the DOM traversal tree, this method traverses in both directions forward and backward along the siblings of the DOM tree nodes.
  • To traverse the only the backward DOM elements or previous siblings of the selected element, use prev() jQuery method.
  • To traverse the only the forward DOM elements or next siblings of the selected element, use next() jQuery method.

Related Topics:

jQuery parents
jQuery parent

jQuery siblings

Syntax:

$(selector).siblings(filter) ;

Parameter description:

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

Example:

In this example we will return all siblings <h3> elements 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{
background:yellow;
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").siblings("h3,div").css("border","2px solid red");
});
});
</script>
</head>
<body>

<h2> jQuery siblings() method Example </h2>
<h3> This heading is sibling of div tag </h3>
<div>
<h3> This is heading of first div </h3>
</div>
<h3> This heading is sibling of div tag </h3>
<button> Click Me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Leave a Reply


Comments
    Waiting for your comments