Reputation: 1671
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?
<div id="myDiv">
<span id="firstValue"> 5.22 <span id="nestedValue"> 500 </span></span>
</div> <!-- myDiv -->
Upvotes: 3
Views: 15509
Reputation: 566
This can also be done like so...
document.getElementById("firstValue").textContent;
Which will give you the text content without the html.
Upvotes: 0
Reputation: 71
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
Upvotes: 1
Reputation: 5857
Here is a simple function for that purpose, and with error handling for the case the span would not exist or would be empty:
function getFirstValue() {
var spanFirstValue = document.getElementById("firstValue");
if (spanFirstValue) {
var textNode = spanFirstValue.childnodes[0];
if (textNode) {
return textNode.data;
}
}
return "";
}
Upvotes: 0
Reputation: 324707
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;
Upvotes: 6
Reputation: 114417
var nodeValue = document.getElementById("firstValue").innerHTML
this will = "5.22 <span id="nestedValue"> 500 </span>
"
Upvotes: 2