Excuse me for the very cryptic name but this is the weirdest (although very small) problem I've ever encountered.

I have a variable in JavaScript which I want to initialize to the int value of 5 to be later incremented in a function. Everything works perfectly until instead of declaring this value in the javascript, I instead pull it from the xml file and assign it to that variable.

This works...

var x = 5;

This doesn't...

var x = xmlDoc.getElementsByTagName("x")[0].childNodes[0].nodeValue;

The weird thing is that when I try to get the output at both by putting a


after the code they both say they are initialized to 5 so what is going on here?

A similar problem is when I get a number from xml, i.e. 20, then I add 1 to that number and then when I print it, the number has for no reason turned into 200.

Recommended Answers

All 4 Replies

try parseInt(xmlDoc.getElementsByTagName("x")[0].childNodes[0].nodeValue); one be a string containing a number, one be a number

Seriously thought I was gonna have to write about 50 extra lines to do this. Thanks a lot for that!

...but perhaps you need an explanation, for why is it happening -so you'll know it before it happens in the future. No html element will ever contain other data-type except a text, which when returned is of type string. therefore a returned 5 is not a number, its a literal, which perhaps when read by human who understands cursive numbers will know it as a literal representation of a number whose explicit value is 5.

To cut it short, with this thing in mind when a retrieved value is supposed to be passed as a numerical value from a textual source you can omit the parseInt function same as you would the Number constructor [which is more semantic and true to its nature] by forcing it with a short and single sign operator as in the following line of code:

var x = +xmlDoc.getElementsByTagName("x")[0].childNodes[0].nodeValue;

x= + yourlongargument; will immediately force a proper duck-type conversion of a given number literal so you wont be needing a parseInt(verylongargument) or Number(equallylongargument);

Note: the +arg will successfully convert "5"; " 5"; "5 " or " 5 " to Number, but not "5px" and alike.

Yes, thanks for that long explanation. I understood why this problem was and if this was another language such as Java where I knew all the functions available I wouldn't have had a problem. But I understand why the problem is caused though but still, that's a good explanation for others in my situation.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.