.children() – How to work with jQuery Children Method

.children() – How to work with jQuery Children Method

The jQuery Children method – .children() gives all the direct children of the selected element.

jQuery Children Method – Syntax

$(selector).children(filter)

filter is used to narrow down the direct children search.

Related to this: Learn to use jQuery Parents Method – .parents() for DOM Traversal

Check the examples below.

jQuery Children example 1

I have a ul that has 2 li as direct children. Each of these li has 1 label.

<ul>
    Parent
    <li>
        Direct Child
        <label>Grand Child</label>
    </li>
    <li>
        Direct Child
        <label>Grand Child</label>
    </li>
</ul>

If I use the jQuery .children() on the ul element then both the li elements will be selected.

So the below jQuery code will create a border on these 2 li elements.

$("ul").children().css({ "color": "aquamarine", "border": "solid 2px #0184e3" }); 
Related to this: Use jQuery Parent Method to select a parent of any element.

jQuery Children example 2 – with ‘filter’

Let me show you how to use the filter parameter of the .children() method.

See the below HTML code:

<ul>
    Parent
    <li id="first">
        Direct Child
        <label>Grand Child</label>
    </li>
    <li id="second">
        Direct Child
        <label>Grand Child</label>
    </li>
</ul>

The direct children have now the ids given to them. To add the border on the li with id ‘first’, I will provide this id to the filter parameter.

$("ul").children("#first").css({ "color": "aquamarine", "border": "solid 2px #0184e3" });

Download link:

DOWNLOAD

Next one: How to use jQuery Toggle Method to show/hide any element with or without animations.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate