With jQuery, you can use the find() to search through all the descendants(child, grandchild, great-grandchild…any levels deep) of the matched element.

For example, div elements with three levels deep.

<div id="A1">
 
	<div class="child">A1-1</div>
	<div class="child">A1-2</div>
 
	<div id="A2">
 
		<div class="child">A2-1</div>
		<div class="child">A2-2</div>
 
		<div id="A3">
 
			<div class="child">A3-1</div>
			<div class="child">A3-2</div>
 
		</div>
 
	</div>
 
</div>

1. $(‘#A1′).find(‘.child’)

$('#A1').find('.child').css('background','red');

Find an element which contains the id of “A1“, and its child element that contains the class name of “child“, then change its background to red.

2. $(‘#A2′).find(‘.child’)

$('#A2').find('.child').css('background','red');

Find an element which contains the id of “A2“, and its child element that contains the class name of “child“, then change its background to red.

3. jQuery find() example

Play this example.

HTML 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 find() example</h1>
 
<script type="text/javascript">
 
  $(document).ready(function(){
 
    $("#button1").click(function () {
 
	$('div').css('background','white');
 
	$('#A1').find('.child').css('background','red');
 
    });
 
    $("#button2").click(function () {
 
	$('div').css('background','white');
 
	$('#A2').find('.child').css('background','red');
 
    });
 
    $("#button3").click(function () {
 
	$('div').css('background','white');
 
	$('#A3').find('.child').css('background','red');
 
    });
 
  });
</script>
</head>
<body>
 
<div id="A1">A1
	<div class="child">A1-1</div>
	<div class="child">A1-2</div>
 
	<div id="A2">A2
		<div class="child">A2-1</div>
		<div class="child">A2-2</div>
 
		<div id="A3">A3
			<div class="child">A3-1</div>
			<div class="child">A3-2</div>
		</div>
	</div>
 
</div>
 
<br/>
<br/>
<br/>
 
<input type='button' value='find #A1' id='button1'>
<input type='button' value='find #A2' id='button2'>
<input type='button' value='find #A3' id='button3'>
 
</body>
</html>

Reference

  1. jQuery find() API documentation
Tags :
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 making a donation to this charity, thanks.

Related Posts

Popular Posts