Explain sibling in jquery with example
In jQuery, the siblings() method is used to get all sibling elements of each element in the set of matched elements, optionally filtered by a selector. Sibling elements are those that share the same parent.
Basic Usage
The syntax for the siblings() method is:
$(selector).siblings([filter])
selector: Specifies the current element.filter(optional): A selector expression to narrow down the matched siblings.
Example
Let's say we have the following HTML structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Siblings Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
// Select the element with id 'item2' and find its siblings
$("#item2").siblings().css("background-color", "yellow");
// Select the element with id 'item2' and find its siblings with class 'highlight'
$("#item2").siblings(".highlight").css("color", "red");
});
</script>
</head>
<body>
<ul>
<li id="item1">Item 1</li>
<li id="item2">Item 2</li>
<li id="item3" class="highlight">Item 3</li>
<li id="item4" class="highlight">Item 4</li>
<li id="item5">Item 5</li>
</ul>
</body>
</html>
Explanation
-
$("#item2").siblings().css("background-color", "yellow");- This selects the element with the ID
item2and applies a yellow background color to all of its siblings (item1,item3,item4, anditem5).
- This selects the element with the ID
-
$("#item2").siblings(".highlight").css("color", "red");- This selects the element with the ID
item2and applies a red text color to its siblings that have the classhighlight(item3anditem4).
- This selects the element with the ID
Output
When the page loads, the resulting visual changes will be:
item1,item3,item4, anditem5will have a yellow background.item3anditem4will have red text.
This demonstrates how the siblings() method can be used to select and manipulate sibling elements in the DOM using jQuery.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
