When you want to apply the style to the child element of the list, div, etc. jQuery child element selector is the best way to select the child element of any parent. You can select all direct children or the specified child of the parent element.
jQuery Child Element Selector by Tag Name
To select the child of the parent element, you have to specify the tag name of both the elements with the parent > child combination.
Use the below syntax of jQuery to get the way to write the combination.
Let’s take an example to apply the style to an HTML p tag which is the direct children of the span tag.
Example
1 2 3 4 5 6 7 8 |
<script> $(document).ready(function(){ $("span > p").css('color','green'); }); </script> <span> <p>This is the paragraph</p> </span> |
Output
This is the paragraph
The above example applies the style color property to the inner element of the span. You can also apply the style to the list elements using the ul > li combination of the selector. To see the example, learn it with the below section.
Get Children with its Class Name Using jQuery
In addition to the above tag name selector, you can also select the inner item using its class name with parent > child selector. For this, you have to use the value of the class attribute of the parent and child element.
See the syntax below which contains the class name with the parent > child selector.
Example
1 2 3 4 5 6 7 8 9 10 11 |
<script> $(document).ready(function(){ $("ul.my-list > li.my-red-list").css('color','red'); }); </script> <ul class="my-list"> <li>Welcome to my website Tutorialdeep!</li> <li>See live examples to understand the topic.</li> <li class="my-red-list">Free download to quickstart.</li> <li>Learn jQuery with Tutorialdeep.</li> </ul> |
Output
- Welcome to my website Tutorialdeep!
- See live examples to understand the topic.
- Free download to quickstart.
- Learn jQuery with Tutorialdeep.
The above example applies the red color to the third child of the list element.