jQuery Child Selector

The direct descendant combinator (>) is used to select the child elements. This combinator expects two selectors, one on either side. It gets the set of elements which is direct children of the selected elements.

Syntax of child selector

$("parent > child ") 

Here, parent is the parent element and child is the direct child element. Both parameters are required.

Example

<section>
<i>Test Children Selector 1.</i></br>
<i>Test Children Selector 2.</i></br>
<span>
<i>Test Children Selector 3.</i></br>
<i>Test Children Selector 4.</i></br> 
</span>
</section>
<i>This text is outside of div element.</i>

<script>
$(document).ready(function(){
$("section > i").css("color", " red");
});
</script>

Output of the above code

Test Children Selector 1.
Test Children Selector 2.
Test Children Selector 3.
Test Children Selector 4.
This text is outside of div element.

In the above example, direct italic elements within the section element text color is set to red while the italic elements within the span element and outside of the section element remains same. The italic elements within the span in also the child of section, but these are not the direct child.

Example

<a href="#">Test</a>
<div>
<a href="#">Demo</a>
</div>

<script>
$(document).ready(function(){
$('div > a').css("color", "blue");
});
</script>

Output of the above code

Test
Demo

Here, we want to select only the anchors within the div element.





Read more articles


General Knowledge



Learn Popular Language