Reputation: 155
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.
Upvotes: 3
Views: 154
Reputation: 14580
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, '');
Upvotes: 2
Reputation: 14031
Using 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
Upvotes: 2