children method in jQuery with example


1. children() method gets the children of each element in the set of matched elements.
2. The children() method allows us to search through children of given jQuery object elements, to construct a new jQuery object of matched elements.
3. The children() differs from find() method. children() method traverse only to single level in the DOM tree structure, while find() method can traverse multiple levels.


Example 1 :

        <html>
        <head>
        <title>children</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 () {
                $("#entireDiv").click(function () {
                    $(".targetDiv").css({ 'color': 'red', 'background-color': 'orange' });
                });
                $("#children").click(function () {
                    $(".targetDiv").children().css({ 'color': 'red', 'background-color': 'orange' });
                });
                $("#reset").click(function () {
                    location.reload();
                });
            });
        </script>
        </head>
        <body>
        <div class="targetDiv">This is <em>99codingexamples</em></div>
        <div class="targetDiv">I love <b>jQuery</b></div><br /><br />
        <input type="button" id="entireDiv" value="Entire Div" />
        <input type="button" id="children" value="children()"/>
        <input type="button" id="reset" value="Reset" />
        </body>
        </html>
    



In the above examples, we have created two div elements having class attribute set value "targetDiv". We have three buttons as follows : 

Entire Div - On click of this button entire div content is selected in the jQuery object and intended CSS is applied to it.


children() - On click of this button entire div is selected and the selected object is traversed to its children using children() method. CSS in this case is applied to children elements of div element.


reset - This button reloads the window.



Watch Video :




0 comments:

Post a Comment