Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is nodeValue property in JavaScript HTML DOM?
The nodeValue property in JavaScript HTML DOM returns the value of a node. It returns null for element nodes and the actual content for text nodes.
Syntax
node.nodeValue
Return Value
The nodeValue property returns:
- Text nodes: The text content
- Comment nodes: The comment text
-
Element nodes:
null - Attribute nodes: The attribute value
Example: Getting Text Node Value
You can try to run the following code to learn how to get nodeValue property.
<!DOCTYPE html>
<html>
<body>
<p>Get the node value</p>
<button>Demo Button Text</button>
<script>
var val = document.getElementsByTagName("BUTTON")[0];
var res = val.childNodes[0].nodeValue;
document.write("<br>Node Value: " + res);
</script>
</body>
</html>
Node Value: Demo Button Text
Example: Different Node Types
<!DOCTYPE html>
<html>
<body>
<p id="para">Sample text</p>
<!-- This is a comment -->
<script>
// Element node - returns null
var element = document.getElementById("para");
console.log("Element nodeValue:", element.nodeValue);
// Text node - returns text content
var textNode = element.firstChild;
console.log("Text nodeValue:", textNode.nodeValue);
// Comment node - returns comment text
var comment = document.body.childNodes[3];
console.log("Comment nodeValue:", comment.nodeValue);
</script>
</body>
</html>
Element nodeValue: null Text nodeValue: Sample text Comment nodeValue: This is a comment
Key Points
-
nodeValueis most useful for text and comment nodes - Element nodes always return
null - Use
firstChild.nodeValueto get text content from elements - Modern alternative:
textContentproperty for element text
Conclusion
The nodeValue property provides access to node content, particularly useful for text and comment nodes. For element text content, consider using textContent as a more direct approach.
Advertisements
