Sunday, 30 September 2018

JavaScript: nodeValue: Get the value of node

‘nodeValue’ property is used to get the value associated with a node.

Syntax
node.nodeValue

nodeValue.html
<!DOCTYPE html>

<html>

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

</head>

<body>
    <p class="color1" id="para1">
        Good Morning
    </p>

    <script>
        var element = document.getElementById("para1");
        alert(element.nodeValue);
    </script>
</body>

</html>


I am trying to get the content in the paragraph tag. Load above page in browser, surprisingly, I got null as the nodeValue. It is because, paragraph element has one child node, which is a text node. To access the content ‘Good Morning’, I need to call nodeValue property on the child node of paragraph.

Update nodeValue.html like below.

nodeValue.html
<!DOCTYPE html>

<html>

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

</head>

<body>
    <p class="color1" id="para1">
        Good Morning
    </p>

    <script>
        var element = document.getElementById("para1");
        var childNodes = element.childNodes;
        alert(childNodes[0].nodeValue);
    </script>
</body>

</html>

Open above page in browser, you can able to see the message ‘Good Morning’ in alert box.


Previous                                                 Next                                                 Home

No comments:

Post a Comment