You are here

jQuery .children()

Access the HTML elements within another element using the jQuery .children() function. In this example we access the list items, <li></li>, in a list, <ul></ul>.

The test data

We use the following HTML list for this test. The list has an id so jQuery can locate our test.

  • Item a
  • Item b
  • Item c

The HTML in the test data

The list contains the following HTML. The outer element, the ul, has an id so jQuery can locate the list element as the parent. jQuery can then access the list items, the li elements, as the children.

<ul id="test-parent" class="parent">
    <li class="child">Item a</li>
    <li class="child">Item <strong>b</strong></li>
    <li class="child">Item c</li>
</ul>

Select the parent

The following jQuery selects the outer element, the parent, using id test-children

jQuery("#test-children")

Select the children

The following jQuery is expanded to find the children using .children(). We now have a list of children in jQuery format.

jQuery("#test-children").children()

Process each child

The following jQuery steps through each child using .each(). We can add Javascript or jQuery code inside .each()

jQuery("#test-children").children().each();

Use a function

The following code shows .each() containing an empty function ready for your code.

jQuery("#test-children").children().each(function() {
});

Process the child

The following code shows this, the child object passed into the function. We can test the child object to see what we have.

jQuery("#test-children").children().each(function() {
  this
});

Display the child

The following code shows the way we add the first line to the results table. this is displayed as [object HTMLLIElement].

jQuery('#test-children').children().each(function() {
  jQuery('#test-result').append("jQuery('#test-parent')" + index + 'this' + this + '');
});

The results

The following table shows the jQuery options we are testing and the results. Note that we are seeing the children, not the grandchildren. We do not see <strong>b</strong> listed as a child because it is the child of a list item, not the list. The .text() function returns only the text, not HTML. .text() returns the text in the <strong>b</strong> element but not the HTML.

Parent Child Test Result