display child elements and their text using jQuery

Getting the child elements of any HTMT element is very difficult in normal javascript. But it is very easy by using jQuery.

 

In the below code I explain how to display child elements by using jQuery.

 

<html>
  <head>
  <title>This is jquery example for displaying the number child elements and their text for given parent element</title>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
        var $nodes = $('#parent').children();
        alert('Number of Elements for given tag: ' + $nodes.length);
        var txt = "";
        $('#parent').children().each(function() {
            txt += $(this).text() + '\n';
        });
        alert('Text of all elements:\n\n' + txt);
        alert('This is "p" tag text:\n\n' + $('#pid').text());
    });   
  </script>
  </head>
  <body>
      <div id="parent">
           <div>First Element</div>
           <div>Second Element</div>
           <div>Third Element</div>
           <div>Fourth Element</div>
      </div>
      <p id="pid">This is from 'p' tag</p>
   </body>
</html>

Here children() jQuery function to get the childs of given parent element. By using $('#parent').children() code, we are getting the child elements of parent element whose id is "parent".

By using text() jQuery function we can get the text of any given element.

 

                               $(document).ready(function() {
                                                   var $nodes = $('#parent').children();
                                                  alert('Number of Elements for given tag: ' + $nodes.length);
                                                           var txt = "";
                                                  $('#parent').children().each(function() {
                                                                      txt += $(this).text() + '\n';
                                                                  });
                                                            alert('Text of all elements:\n\n' + txt);
                                                          alert('This is "p" tag text:\n\n' + $('#pid').text());
                                                    });   

 

In the above code we display the child elements of "parent" id parent element using children() jQuery function and their text by using text() jQuery function. At the end I also display the individual <p> tag text whose id is "pid".

 

Download source code: third jQuery exmp.zip (35.80 kb)