Skip to content Skip to sidebar Skip to footer

Javascript: Getting Node Value

I am pretty new to Javascript and I need to get the value of the node with id firstvalue so that I can use it in my script. Can anyone please tell me how do I get that value? <

Solution 1:

document.getElementById("firstValue") will get you a reference to the <span>. This has two child nodes, which you can reference via the array-like childNodes property, or in this case simply using firstChild and lastChild properties. For example, the following will return you the string " 5.22 ":

document.getElementById("firstValue").firstChild.nodeValue;

Solution 2:

var nodeValue = document.getElementById("firstValue").innerHTML

this will = "5.22 <span id="nestedValue"> 500 </span>"

Solution 3:

Many javascript libraries are helping a lot in accessing DOM elements, such as: prototype, dojo, jQuery to name a few. In prototype you would type: $('firstValue').firstChild.nodeValue

Solution 4:

Here is a simple function for that purpose, and with error handling for the case the span would not exist or would be empty:

functiongetFirstValue() {
    var spanFirstValue = document.getElementById("firstValue");
    if (spanFirstValue) {
        var textNode = spanFirstValue.childnodes[0];
        if (textNode) {
            return textNode.data;
        }
    }
    return"";
}

Solution 5:

This can also be done like so...

document.getElementById("firstValue").textContent;

Which will give you the text content without the html.

Post a Comment for "Javascript: Getting Node Value"