Use DIV value in Javascript method to perform calculation
The following <div>
returns an integer between 0-1
.
<div id=value></div>
The above DIV returns a number, for example: 0.75.
I want to use this return value in a javascript method. How can i do this?
function getRandomArbitrary() {
def number =Math.random() * <<THE VALUE THAT I OBTAINED FROM THE ABOVE DIV TAG>>;
return number;
}
source to share
Assuming you want the value inside the tag, for example <div id=value>1</div>
, you can use .innerHTML
. To ensure that the inside of the div is, in fact, a floating point number, wrap it in parseFloat
(for example, if the div contains "abc", parseFloat will return 0).
In your case:
function getRandomArbitrary() {
var number =Math.random() * parseFloat(document.getElementById('value').innerHTML);
return number;
}
source to share
function getRandomArbitrary(elID) {
return Math.random() * parseFloat(document.getElementById(elID).innerHTML);
}
getRandomArbitrary("number");
The above is in case you have something like:
<div id=number>0.75</div>
If you really want to store the value inside the DIV , then a good way to do it is to use
data-*
:
<div id=number data-value="0.75"></div>
will change the code:
parseFloat(document.getElementById(elID).dataset.value);
source to share