The jQuery Children method – .children() gives all the direct children of the selected element.
$(selector).children(filter)
filter is used to narrow down the direct children search.
Check the examples below.
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" });
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: