Jquery Siblings
In jQuery, siblings are the elements that share the same parent element as the selected element. To select siblings of an element, we can use the .siblings() method.
The .siblings() method selects all the siblings of the selected element, excluding the element itself. Here’s an example:
<!DOCTYPE html> <html> <head> <title>jQuery Siblings Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> ul { list-style-type: none; padding: 0; } li { padding: 5px; border: 1px solid black; } .active { background-color: yellow; } </style> </head> <body> <h2>jQuery Siblings Example</h2> <ul> <li>Item 1</li> <li class="active">Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> <script> $(document).ready(function() { // Select all the siblings of the active list item $(".active").siblings().css("background-color", "gray"); }); </script> </body> </html>
In this example, we have an unordered list with several list items. We use jQuery to select all the siblings of the active list item using the .siblings() method and change their background color to gray.
We can also use a selector with the .siblings() method to select only specific siblings. Here’s an example:
<!DOCTYPE html> <html> <head> <title>jQuery Siblings Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> ul { list-style-type: none; padding: 0; } li { padding: 5px; border: 1px solid black; } .active { background-color: yellow; } .highlight { background-color: lightblue; } </style> </head> <body> <h2>jQuery Siblings Example</h2> <ul> <li>Item 1</li> <li class="active">Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> <script> $(document).ready(function() { // Select all the siblings of the active list item that have a class of "highlight" $(".active").siblings(".highlight").css("background-color", "gray"); }); </script> </body> </html>
In this example, we use a selector with the .siblings() method to select only the siblings of the active list item that have a class of “highlight” and change their background color to gray.