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
item2
and 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
item2
and applies a red text color to its siblings that have the classhighlight
(item3
anditem4
).
- This selects the element with the ID
Output
When the page loads, the resulting visual changes will be:
item1
,item3
,item4
, anditem5
will have a yellow background.item3
anditem4
will have red text.
This demonstrates how the siblings()
method can be used to select and manipulate sibling elements in the DOM using jQuery.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.