0

I have the following XML :

 <beanRepresentation>
     <beanRepId>222</beanRepId>
     <beanRepName>Bean 1</beanRepName>
     <topY>10</topY>
     <leftX>10</leftX>
     <height>10</height>
     <width>10</width>
 </beanRepresentation>

This line gets the value of the topY:

document.write(x[i].getElementsByTagName("topY")[0].childNodes[0].nodeValue);

This would give me a 10, but I want a 20, I tried to

document.write(x[i].getElementsByTagName("topY")[0].childNodes[0].nodeValue +10);

but it did not work, it gave me 1010 instead. what can do I do manipulate the number?

PhoonOne
  • 2,228
  • 11
  • 41
  • 64
  • 1
    What do you mean by "it didn't work?" What did it actually do? I suspect that you got something like `1010` as a result, because nodeValue is a string, not a number. – Robert Harvey Jan 16 '14 at 19:14
  • Well, there you go. Javascript saw that `nodeValue` was a string, so it cast your number to a string, and mashed them together. To get real math, you have to convert `nodeValue` to a number. – Robert Harvey Jan 16 '14 at 19:16
  • Got it, thanks for the suggestion. – PhoonOne Jan 16 '14 at 19:18

1 Answers1

1

The value returned by nodeValue is a string (see, e.g., MDN on this), so you're performing string concatenation instead of an addition. You should convert the result to a number before:

document.write( parseInt( x[i].getElementsByTagName("topY")[0].childNodes[0].nodeValue, 10)  + 10);

Anyway, I recommend you read the answers on this question: Why is document.write considered a "bad practice"?

Community
  • 1
  • 1
Sirko
  • 65,767
  • 19
  • 135
  • 167