HI WELCOME TO KANSIRIS

jQuery Traversal.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

1
$(selector).children(filter)
filter is used to narrow down the direct children search.
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.
1
2
3
4
5
6
7
8
9
10
11
<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 for these 2 li elements.
1
$("ul").children().css({ "color": "aquamarine", "border": "solid 2px #0184e3" });

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:

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:
1
2
3
4
5
6
7
8
9
10
11
<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.
1
$("ul").children("#first").css({ "color": "aquamarine", "border": "solid 2px #0184e3" });