firstChild property contains the first child DOM node of a DOM node, which could be of type
For example, the below code changes the text in the first
<li> element from “Gas” to “Water”.
<ul id="example"><li>Gas</li><li>Food</li></ul> <script> const list = document.querySelector('#example'); list.firstChild.innerHTML = 'Water'; </script>
Whitespace matters when using
The below example does not work as expected, because
firstChild returns a text node containing the whitespace between
<ul id="example"> and the first
<ul id="example"> <li>Gas</li> <li>Food</li> </ul> <script> const list = document.querySelector('#example'); // 'firstChild' below is a text node containing whitespace, **not** the first '<li>' list.firstChild.innerHTML = 'Water'; </script>
You can use the
firstElementChild property to avoid this issue, and get the first DOM element node, ignoring text nodes.
<ul id="firstElemChild"> <li>Gas</li> <li>Food</li> </ul> <script> const elem = document.querySelector('#firstElemChild'); elem.firstElementChild.innerHTML = 'Water'; </script>
If the DOM node has no children,
<div id="example1"></div> <script> // Prints "null" console.log(document.querySelector('#example1').firstChild); </script>
- Variables: Variables are used to store data. They are declared using the
- Operators: Operators are used to perform operations on data.
- Control flow statements: Control flow statements allow you to control the order in which your code is executed.
- Functions: Functions are blocks of code that can be reused.
- Objects: Objects are used to store data in key-value pairs.
- Arrays: Arrays are used to store data in a sequential order.
- Events and event handlers: Events are notifications that are sent by the browser when something happens, such as when the user clicks on an element or moves the mouse over an element. Event handlers are functions that are called in response to an event.
I hope this helps!