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:
<div id="div1">
<p>This is the first child of #div1</p>
<p>This is the second child of #div1</p>
<p>This is the third child of #div1</p>
<p>This is the fourth child of #div1</p>
</div>
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.
<div id="div1">
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p>This is paragraph 3</p>
</div>
<div id="click-me">Change background</div>
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:
<div id="div1">
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p>This is paragraph 3</p>
</div>
<div id="click-me">Change background</div>
<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.
Leave a Reply