over 9 years ago
These methods are used to select the child node of the matched elements.
See the below examples to understand the difference between find() and children():-
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>find demo</title>
- <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
- </head>
- <body>
- <p><span>Hi</span>, what are you doing?</p>
- <p> I'm <span>working</span>.</p>
- <script>
- $(document).ready(function(){
- $( "p" ).find( "span" ).css( "color", "red" );
- });
- </script>
- </body>
- </html>
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>find demo</title> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p><span>Hi</span>, what are you doing?</p> <p> I'm <span>working</span>.</p> <script> $(document).ready(function(){ $( "p" ).find( "span" ).css( "color", "red" ); }); </script> </body> </html>
In this example, all the content inside the span tag (which is inside p tag) will be displayed in red color.
- <html>
- <head>
- <title>children demo</title>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
- <script>
- $(document).ready(function(){
- $("div").children(".first").addClass("orange");
- });
- </script>
- <style>
- .orange { color:orange; }
- </style>
- </head>
- <body>
- <div>
- <span>Hello</span>
- <p class="first">Hello everyone</p>
- <div class="first">And how are you</div>
- <p class="second">And what are you doing</p>
- </div>
- </body>
- </html>
<html> <head> <title>children demo</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("div").children(".first").addClass("orange"); }); </script> <style> .orange { color:orange; } </style> </head> <body> <div> <span>Hello</span> <p class="first">Hello everyone</p> <div class="first">And how are you</div> <p class="second">And what are you doing</p> </div> </body> </html>
This would apply blue color to all children with a class "first" of each div.
Therefore,there isn't much performance difference in typical cases.Which one to use depends on which elements and what levels you want to traverse down in the DOM. Use any method according to the result you desire.
Can you help out the community by solving one of the following Javascript problems?
Do activity (Answer, Blog) > Earn Rep Points > Improve Rank > Get more opportunities to work and get paid!
For more topics, questions and answers, please visit the Tech Q&A page.
0 Comment(s)