To get the first child of an HTML element, we can use the firstElementChild property and use JavaScript to make changes to that element.

document.getElementById("div1").firstElementChild;

Let’s say we 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 firstElementChild property and use the following JavaScript code:

document.getElementById("div1").firstElementChild.style.backgroundColor = "#c1e9c1";

How to Get the First Child on Click using JavaScript

We can get the first child of an HTML element using JavaScript very easily by combining the firstElementChild property 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 firstElementChild property, and the backgroundColor property 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.

function changeBG() {
  document.getElementById("div1").firstElementChild.style.backgroundColor = "#c1e9c1";
}

The final code and output for this example is below:

Code Output:

This is paragraph 1

This is paragraph 2

This is paragraph 3

Change background

Full Code:

This is paragraph 1

This is paragraph 2

This is paragraph 3

Change background
<script> function changeBG() { document.getElementById("div1").firstElementChild.style.backgroundColor = "#c1e9c1"; } </script>

Hopefully this article has been useful to help you understand how to get the first child element and change it with JavaScript

Categorized in:

JavaScript,

Last Update: March 20, 2024