jQuery children() example
In jQuery, children() is used to find the child of the matched elements, it’s only travels a single level down.
For example, div elements with three levels deep, contains a class name of “child” and “orphan”.
<div class="A1"> <div class="child">A1-1</div> <div class="child">A1-2</div> <div class="orphan">A1-3</div> <div class="child">A1-4</div> <div class="A2"> <div class="child">A2-1</div> <div class="child">A2-2</div> <div class="A3"> <div class="child">A3-1</div> <div class="child">A3-2</div> </div> </div> </div>
1. $(‘.A1′).children()
$('.A1').children().css('background','red');Match elements that contains a class name of “A1“, and all the A1 “single level child“.
P.S The A2 and A3 child will be ignore.
2. $(‘.A1′).children(‘.child’)
$('.A1').children('.child').css('background','red');Match elements that contains a class name of “A1“, and search through the “A1” child that contains a class name of “child”. In this example, all the A1 “single level child” except child with a class name of “orphan” will be select.
jQuery children() example
<html> <head> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <style type="text/css"> div{ padding:8px; border:1px solid; } </style> </head> <body> <h1>jQuery children() example</h1> <script type="text/javascript"> $(document).ready(function(){ $("#buttonChildren1").click(function () { $('div').css('background','white'); $('.A1').children().css('background','red'); }); $("#buttonChildren2").click(function () { $('div').css('background','white'); $('.A1').children('.child').css('background','red'); }); }); </script> </head><body> <div class="A1"> <div class="child">A1-1</div> <div class="child">A1-2</div> <div class="orphan">A1-3</div> <div class="child">A1-4</div> <div class="A2"> <div class="child">A2-1</div> <div class="child">A2-2</div> <div class="A3"> <div class="child">A3-1</div> <div class="child">A3-2</div> </div> </div> </div> <br/> <br/> <br/> <input type='button' value='.A1 children()' id='buttonChildren1'> <input type='button' value='.A1 children(child)' id='buttonChildren2'> </body> </html>
1. $(‘.A1′).children().css(‘background’,'red’);
P.S The A2 and A3 child will be ignore.
? Testing in IE8 & Safari 5.0.2, the background color of A2 and A3 child will also be red.