Sunday 30 September 2018

JavaScript: firstChild, lastChild: get first and last Chids of a node

'firstChild' property return the first child of an element. ‘lastChild’ property return the last child of an element.

Syntax
node.firstChild
node.lastChild

nodeValue.html
<!DOCTYPE html>

<html>

<head>
    <title>Node Value</title>

</head>

<body>
    <p class="color1" id="para1">
        <span>I am first child</span>
        <span>I am second child</span>
        <span>I am third child</span>
    </p>

    <script>
        var element = document.getElementById("para1");
        var pChildNodes = element.childNodes;

        alert(pChildNodes.length);
        alert(pChildNodes[1].firstChild.nodeValue);
        alert(pChildNodes[3].firstChild.nodeValue);
        alert(pChildNodes[5].firstChild.nodeValue);
    </script>
</body>

</html>

Open above page in browser, you can able to see total child nodes as 7 (It is because, white space also considered as child, total 4 white space and 3 spac childs) and the messages like I am first child, I am second child, I am third child. 

In the same way, how you access the value associated with a node, you can also set the value to a node using nodeValue property.

nodeValue.html

<!DOCTYPE html>

<html>

<head>
    <title>Node Value</title>

</head>

<body>
    <p class="color1" id="para1">
        <span>I am first child</span>
        <span>I am second child</span>
        <span>I am third child</span>
    </p>

    <script>
        var element = document.getElementById("para1");
        var pChildNodes = element.childNodes;

        alert(pChildNodes.length);
        alert(pChildNodes[1].firstChild.nodeValue);
        alert(pChildNodes[3].firstChild.nodeValue);
        alert(pChildNodes[5].firstChild.nodeValue);

        pChildNodes[1].firstChild.nodeValue = "Good Morning"
        pChildNodes[3].firstChild.nodeValue = "Good Afternoon"
        pChildNodes[5].firstChild.nodeValue = "Good Evening"
    </script>
</body>

</html>


Previous                                                 Next                                                 Home

No comments:

Post a Comment