문제

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!

도움이 되었습니까?

해결책

You can use unary operator + for convert string to number something like

var results = +(document.getElementById("searchResults").innerHTML);
//------------^

Also you forgot to use .innerHTML

다른 팁

  1. You have to actually get the innerHTML (you are currently looking at the HTML element node)
  2. You can use 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);
}

Demo

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top