You can use unary operator +
for convert string to number something like
var results = +(document.getElementById("searchResults").innerHTML);
//------------^
Also you forgot to use .innerHTML
Question
I'm making a script, in which i have to use an inner.HTML which is a number, and work with it mathematically. Here's the example:
<span id="searchResults">2301</span>
As you can see, the inner.HTML is a number, and I'd like to make a script like:
var results = document.getElementById("searchResults");
if (results > 3000)
{
location.reload(true);
}
Of course this isn't possible because the script doesn't see the inner.HTML as a number it can mathematically work with.
So, is there a way to convert the inner.HTML into a number I can do math with?
Thanks for helping!
Solution
You can use unary operator +
for convert string to number something like
var results = +(document.getElementById("searchResults").innerHTML);
//------------^
Also you forgot to use .innerHTML
OTHER TIPS
parseInt
, parseFloat
or the Unary +
Operator (but you probably don't need to since >
is quite smart when the LHS is a number).Such:
var results = document.getElementById("searchResults");
var results_num = parseInt( results.innerHTML, 10 );
You probably need .innerHTML
, as without .innerHTML
your results
will contain HTMLspanobject
you have to do innerHTML
var results = document.getElementById("searchResults").innerHTML;
alert(parseInt(results));
if (parseInt(results,10) > 3000)
{
alert("te");
// location.reload(true);
}
var results = document.getElementById("searchResults").innerHTML;
if (parseInt(results) > 3000)
{
location.reload(true);
}
InnerHtml returns string content. You need to convert it to a number/integer.
var results = document.getElementById("searchResults");
if (results != null && parseInt(results.innerHTML) > 3000)
{
location.reload(true);
}