0

HTML + JavaScript beginner here.

I'm trying to getElementById, a number in my case. I can only achieve NaN, Undefined or some strange text about an object.

I want the element's number and return it with the power of 2. 144. Thank you!

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript Test</title>
        <script src="test.js"></script>
    </head>

<body>
    <p id="number">12</p>
    <button id="button1" onclick="calcSquare()">Click here!</button>
</body>

</html>

function calcSquare() {
  var a = document.getElementById('number').value;
  var b = 2;
  document.getElementById('number').innerHTML = (Math.pow(a, b));
  }

1 Answers1

0

Your id="numer" element is a p, not an input or a select, so it doesn't have a value property. You could use its textContent property, which gives you the text of its content:

var a = document.getElementById('number').textContent;

Or alternatively use an input type="text" instead, so it has a .value.

Whether you use textContent or value, you'll always get a string. You could rely on Math.pow to implicitly convert that to number, but I generally find it's best to convert on purpose. My answer here goes into your various options for that.

I also recommend not using onxyz-attribute-style event handlers. Instead, hook up the event via modern mechanisms like addEventListener. That way, the handler doesn't have to be a global function.

(There's also no need for the () around Math.pow(a, b).)

Here's an example using a contenteditable p element:

document.getElementById("button1").addEventListener("click", function calcSquare() {
    const el = document.getElementById("number");
    const a = +el.textContent;
    const b = 2;
    el.textContent = Math.pow(a, b);
});
<p id="number" contenteditable>12</p>
<button id="button1">Click here!</button>

In that I've used const rather than var. There's basically no place for var in modern JavaScript programming.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    This was an amazing help. I researched into everything you explained and found it valuable. Everything works! Thank you. – JustaStudent Mar 29 '21 at 19:24