jQuery – General sibling selector example

jQuery general sibling selector (X ~ Y) is used to select all elements matched by “Y” that is a sibling of a “X” element.

For example,

<div class="class1"></div>
<p>I'm class1 sibling #1</p>
<p>I'm class1 sibling #2</p>
<p>I'm class1 sibling #3</p>

The <div> and <p> are in sibling relationship. The “$(.class1 ~ p)” statement will select all the <p> elements.

jQuery Example

In this example, Both <div> tag with value “I’m form siblings #1 – DIV” and <div> tag with value “I’m form siblings #3 – DIV” are matched, because they are the siblings elements of <form>.

<title>jQuery general sibling selector example</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
 <style type="text/css">
  div { padding:8px 0px 8px 8px; }
<script type="text/javascript">
	$("form ~ div").css("border", "2px solid red");
<h1>jQuery general sibling selector example</h1>
	<label>TextBox 1 (Child) : </label><input name="textbox1">
	<div class="level1">
		<label>TextBox 2 (GrandChild) : </label><input name="textbox2">
	<div class="level1">
	 <div class="level2">
	   <label>TextBox 3 (Great GrandChild) : </label><input name="textbox3">
	<label>TextBox 4 (Child) : </label><input name="textbox4">
<div> I'm form siblings #1 - DIV</div>
<p> I'm form siblings #2 - P </p>
<div> I'm form siblings #3 - DIV </div>
<p> I'm form siblings #4 - P </p>
Tags :

About the Author

Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.