Given the circumstances I have to use a node list to get at elements that I need to work with. I am able to use .textContent (or .nodeValue) to return a string that I need, but I am having trouble finding a way to get that string into any type of number. I need to have it in number form so I can perform calculations with it. I have tried Number(), parseInt(), etc. All return NaN. I am pretty new to JS so hopefully this is an easy issue to solve.
var siteActual = tdNodeListActual[36].textContent; // location of data
console.log(siteActual); // returns the value 1 as it should
var asd = Number(siteActual); // test variable to convert string to number
console.log(asd); // returns NaN
EDIT: I checked .length as one of you suggested and it was 2, so those saying it may be an invisible character are probably right. I am trying to make changes to a SharePoint page, that is why I am not familiar with what the markup is. Any suggestions on how to remove all but the number would be helpful.
2 Answers 2
Your code should work as-is if the content is really just 1 (as should parseInt). So there must be something other than valid numbers in your content.
Sometimes there can be content that you can't see, e.g. in the example below the second td contains an invisible "zero-width space" character.
var tdNodeListActual = document.querySelectorAll("td");
var good = tdNodeListActual[0].textContent;
var bad = tdNodeListActual[1].textContent;
alert(good + "==" + Number(good) + ", but " + bad + "==" + Number(bad))
<table><tr>
<td>1</td>
<td>​2</td>
</tr></table>
You can remove all non-digit characters (except . and ,) using a regex, e.g.:
siteActual = siteActual.replace(/[^\d.,]/g, '');
6 Comments
[] - I added . and , above, in case you need to deal with international number formatsUsing parseInt(...)
Sample:
var siteActual = tdNodeListActual[36].textContent; // location of data
console.log(siteActual); // returns the value 1 as it should
var asd = Number(parseInt(siteActual)); // test variable to convert string to number
console.log(asd); // should return 1
parseInt(String)parseInt(...)- on which element? I suppose more details would be necessary (i.e. some HTML sample on where you are getting the value from to begin with)siteActual.lengthand see if it's what you expect