简体   繁体   中英

Use an inner.HTML mathematically?

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

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

  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 );
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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM