简体   繁体   中英

How to get a value from inside of an element in HTML and set it as variable in JS

Here I have an element.

<span id="coins">50</span>

And I want to get the 50 out of it and set it as x (something like that)

var x = ("#coins")

But I'm not sure how to do it...

I'm going to assume that you want x to end up as a number, so you could do this:

var x = +(document.getElementById("coins").innerHTML)

Which will get the innerHTML of the element, then convert it to a number using the unary + .

This also works:

var x = parseFloat((document.getElementById("coins").innerHTML));

var x = parseInt((document.getElementById("coins").innerHTML), 10);

There is also an innerText as well as .textContent property, but they doesn't have as wide of support.

You can access the innerHTML of the element like so:

var spanEl = document.getElementById('coins');
var x = spanEl.innerHTML;

If you want to cast it to an int you can use parseInt :

var spanEl = document.getElementById('coins');
var x = parseInt(spanEl.innerHTML, 10);

Note that 10 is the second argument in the parseInt function. That indicates that you want to parse the number base 10.

Can't properly style it in the comments, but this is what I would recommend doing:

var x = parseInt(document.getElementById("coins").childNodes[0].nodeValue); 

x = isNaN(x) ? 0 : x;

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