find method in jQuery with example
1. find() method gets the descendants of each element in the current set of mathed elements, filtered by a selector, jQuery object or an element.
2. Consider a jQuery object representing a set of DOM elements, the find() method allows us to search through the descendants of these elements in DOM tree and construct a new jQuery object from matching elements.
3. find() and children() method are similar in working, but children() method travels only one level down in DOM tree.
Example 1 :
<html>
<head>
<title>find</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#myButton").click(function () {
var target = $("#target");
$("ul").find(target).css({ 'font-size': '28px', 'font-family': 'Arial', 'color': 'Green' });
});
});
</script>
</head>
<body>
<ul type="circle">
<li>Cesc Fabregas</li>
<li id="target">Thierry Henry</li>
<li>Robin Van Persie</li>
<li>Tomas Rosicky</li>
</ul><br />
<input type="button" id="myButton" value="Click ME"/>
<input type="button" value="Reset" onclick="location.reload()"/>
</body>
</html>
Demo :In the above example, we have created list of players. For li element with Thiery Henry as text, we have given an id attribute. On button click, we are selecting entire ul element. Using id selector we are selecting li having id as "target". In the ul object we are finding this li object using find() method and changing its CSS.
Example 2 :
<html>
<head>
<title>find</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#findButton").click(function () {
$("#findDiv").find('em').css({ 'font-size': '40px', 'color': 'Aqua' });
});
});
</script>
</head>
<body>
<div id="findDiv" style="height:100px;">
<p>This is an example for <em>find</em> method.</p>
</div>
<input type="button" id="findButton" value="Click" />
</body>
</html>
Demo :In the above example, we have created a div element and inside that div, we have created one paragraph element. Inside that paragraph element we are using emphasize element i.e <em>.
On button click, we select div element and inside selected object we find its descendants i.e <em> using element selector and changes its CSS.
0 comments:
Post a Comment