In our continuing look at the DOM, I would like to turn our attention to node value. We can utilize this property to pull the value contained within a node and even change the value. So how does this work? I am glad you asked…
<p id="myP">This is my paragraph content.</p>
// Grab the textNode nodeValue within the paragraph
var myP = document.getElementById("myP").firstChild.nodeValue;
alert(myP); // This should alert the text – "This is my paragraph content."
// Set the textNode nodeValue to a new value…this should change it on the screen
document.getElementById("myP").firstChild.nodeValue = "This is new content.";
As I stated in a previous post, we could use innerHTML, but it is not a standard and we want to make certain we follow standards as much as possible. There are other “gotchas” with innerHTML when it comes to reading and writing text, but that is for another post.
In the aforementioned code, you can see that I am grabbing the node value of the text within the paragraph. Notice how I phrased that? Your first thought might be, “Oh…he is grabbing the value of the paragraph.” That is not accurate. In the DOM, every element is a node. So in my code, the paragraph tag is a node and the text within the paragraph is a node. The paragraph is the parent of the text node. The text node is the child of the paragraph node element. So both are node, just different type of nodes. That is why I had to use the firstChild property. I could not simply say, “Give me the value within the paragraph.” I had to tell my code, “Give me the value of the text node.” Since we do not have a way to grab the text node directly via an ID or anything, I had to traverse the DOM utilizing firstChild. So, in essence, I told my code, “Grab the paragraph element and give me the first child inside it, which was my text.” I used the saame method to change the value of the text node.