Home > Mobile >  How do I convert the inner Div text in number?
How do I convert the inner Div text in number?

Time:01-14

<button onclick = "p1Heal()" id="heal">Heal</button>
<div id="p1Health">100</div>

Actually I want to increment the health by some random number between 1-5 so I used the Math.random but it is concatenating the string and the number

I tried doing this:

let p1HealthDiv = document.getElementById('p1Health')
function p1Heal(){
  const p1Heall = Math.floor(Math.random()*5);
  p1HealthDiv.innerHTML  = `${Number(p1Heall)}`
}

but instead it is concatenating with the string i.e 100 the output I am getting is: if the health is 91 it adding (0/1/2/3/4) in the div and displaying as 912I actually want it to increase it to (any number between 0 and 4) like: 94

Might be a stupid question, just a student and new to learning this language and, hoping to get a positive reply from my senior fellows Thank you.

CodePudding user response:

The problem is that you are using the " =" operator to concatenate the value of p1Heall to the existing value of the p1HealthDiv element. Instead, you should use the " " operator to add the value of p1Heall to the existing value.

You can fix this by changing the following line:

p1HealthDiv.innerHTML  = ${Number(p1Heall)} 

to:

p1HealthDiv.innerHTML = Number(p1HealthDiv.innerHTML)   p1Heall;

This will add the value of p1Heall to the existing value of the p1HealthDiv element and update the HTML to reflect the new value.

Another way you can do it is by using the innerText property instead of innerHTML, and do :

p1HealthDiv.innerText = Number(p1HealthDiv.innerText)   p1Heall;

Also, you don't need to use Math.floor as Math.random() returns a decimal number between 0 and 1, so multiplying it with 5 will be between 0 and 4.99, which when rounded down will be between 0 and 4.

You should also make sure that the initial value of the health is a number and not a string, otherwise, you may run into unexpected behavior.

Hope this helps!

CodePudding user response:

The problem you had is that you were trying to add a number to a string. To solve this you need to convert the string to a number and then add them together.

Left some code for you to checkout.

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="p1Health">100</div>
    <button onclick="p1Heal()" id="heal">Heal</button>
    <script>
      let p1HealthDiv = document.getElementById("p1Health");
      function p1Heal() {
        const p1Heall = Math.floor(Math.random() * 5);
        console.log(p1Heall);
        console.log(p1HealthDiv.innerText);
        console.log(typeof p1Heall);
        console.log(typeof p1HealthDiv);
        p1HealthDiv.innerText = parseInt(p1HealthDiv.innerText)   p1Heall;
      }
    </script>
  </body>
</html>

CodePudding user response:

First: It is generally not a good idea to use inline event handlers.

Second: attributes and text within html elements are always strings. So, to to perform calculations with it, you need a step to convert such a value to a real Number. There are several ways to do that (the functions Number, parseInt, parseFloat or simply put before the string). Why? Ecmascript is loosely typed and interprets the addition of a number to a string as string concatenation. See also: MDN.

Third: innerHTML is not necessary here and it even may be unsafe, so use textContent.

Here's a small snippet that takes the aforementioned into consideration. It uses event delegation to handle the button click. As a bonus it contains a random number function that uses the more modern crypto library (see also).

const randomNr = (min = 0, max = Number.MAX_SAFE_INTEGER) => 
  Math.floor( ([...crypto
    .getRandomValues(new Uint32Array(1))][0] / (2 ** 32) ) * 
      (max - min   1)   min );
document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.id === `heal`) {
    const p1Health = document.getElementById(`p1Health`);
    const randomValue = randomNr(0, 5);
    p1Health.textContent =  p1Health.textContent   randomValue;
    //                     ^ conversion
    document.querySelector(`#addDemo`).textContent = `(last added: ${
     randomValue})`;
  }
}
<button id="heal">Heal</button>
<span id="p1Health">100</span> <span id="addDemo"></span>

  • Related