Skip to content
Advertisements

DOM firstChild

The node is an interface that is inherited by a large number of DOM API objects. These types provide similar treatment. If the methods and properties are not relevant, it returns a null value.

  • childNodes: The childNodes method returns a live NodeList containing all its children.
  • firstChild: Returns the first child of the connected node. Returns null if the node does not have a child.
  • lastChild: Returns the last child of the connected node. Returns null if the node does not have a child.
  • parentNode: This method returns a parent node of the specified node as the Node object. This property is read-only.
  • nextSibling: Represents the next node of the connected node. If there is no such node, it returns null.
  • previousSibling: Represents the previous node of the connected node. If there is no such node, it returns null.
  • textContent: Returns the text content of an element.
  • parentElement: This method returns the parent element of the node. If the node has no element, null is returned.
  • isConnected: Checks whether the node is connected to the element. Returns true if bound. Returns false if it is not connected.

HTML DOM firstChild()

Returns the first child of the connected node. Returns null if the node does not have a child.

NOTE: The firstChild property is different than the firstElementChild. The firstChild property returns the first child node. This can be a text or comment node. firstElementChild does not return text and comments.

Syntax:

node.firstChild


firstChild Examples

Example 1

firstChild example
    <ul id="list"><li>BMW</li><li>AUDI</li><li>TESLA</li></ul>

    <button onclick="firstFunction()">SHOW</button>
    <p id="show"></p>

    <script>

        function firstFunction() {
            let list = document.getElementById("list").firstChild.innerHTML;
            document.getElementById("show").innerHTML = list;
        }

    </script>

Example 2

firstChild example
    <div id="box"><p>I love javascript</p><span>HTML DOM</span></div>

    <button onclick="firstFunction()">SHOW</button>
    <p id="show"></p>

    <script>

        function firstFunction() {
            let box = document.getElementById("box").firstChild.nodeName;
            document.getElementById("show").innerHTML = box;
        }

    </script>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: