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

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

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 for these 2 li elements.

$("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:

<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" });

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.