To get the first child of a HTML element using jQuery, the simplest way is with the jQuery :first-child selector.
$("#div p:first-child");
Let’s say I have the following HTML:
This is the first child of #div1
This is the second child of #div1
This is the third child of #div1
This is the fourth child of #div1
To get the first paragraph child of the div, we can use the jQuery :first-child selector and use the following Javascript code:
$("#div1 p:first-child");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1 p:first-child");
How to Get the First Child on Click using jQuery
We can get the first child of an HTML element using jQuery very easily by combining the :first-child selector with a click event.
Let’s say we have the following HTML code and we want to change the background color of the first paragraph.
This is paragraph 1
This is paragraph 2
This is paragraph 3
Change background
We can utilize the jQuery :first-child selector, and the jQuery css() method to change the background of the first paragraph.
Below is the Javascript code which will allow the user to be able to select the first paragraph and set the new background color using jQuery.
$("#click-me").click(function(){
$("#div1 p:first-child").css("background","green");
});
The final code and output for this example of how to change the background of the first child of a div using jQuery and Javascript is below:
Code Output:
This is paragraph 1
This is paragraph 2
This is paragraph 3
Full Code:
This is paragraph 1
This is paragraph 2
This is paragraph 3
Change background
<script>
$("#click-me").click(function(){
$("#div1 p:first-child").css("background","green");
});
</script>
Hopefully this article has been useful to help you understand how to use jQuery to get the first child from a parent HTML element.