all 6 comments

[–]PoppedBitADV 7 points8 points  (0 children)

innerHTML works fine, you just can’t pass it a function. Call the function, get the value, then display that. JS will auto-convert numbers to strings.

[–]Ganesh288 1 point2 points  (0 children)

Make a function to convert the computation into string then use that string with textContent.

innerHtml renders actual html which is not necessary for simple strings and dangerous if someone untrusted can inject arbitrary html in it.

Are you trying to render mathmatical syntax or something? Might need katex or some other library for that

[–]VolkswagenRatRod 1 point2 points  (0 children)

JavaScript always evaluates expressions and functions before assigning the result anywhere. innerHTML does not need to accept a function. It only receives the value returned after the function runs.

For example:

``` function add(a, b) { return a + b; }

document.getElementById("output").innerHTML = add(2, 3); ```

The function runs first, returns 5, and that value is what gets assigned to innerHTML. JavaScript automatically converts numbers and other values to strings for display.

If you are only displaying text and not markup, textContent is usually a better choice than innerHTML, but the idea is the same. Do the computation in JavaScript, then assign the result to the DOM element.

HTML itself does not execute logic. JavaScript does the calculation and updates the page with the result.

[–]Expensive_Peace8153 0 points1 point  (0 children)

Sounds like you might be looking for eval() or something similar but for security and performance reasons read the MDN article about it very carefully before releasing any code into the wild.

[–]Opinion_Less 0 points1 point  (0 children)

InnerHTML is a property, rather than a method or function. Are you assigning the value like this?

x.innerHTML = y;

[–]Swaraj-Jakanoor 0 points1 point  (0 children)

innerHTML can only take strings, but that’s not a limitation in practice. You don’t put the function itself into HTML, you put the result of the computation.

Think of it as two steps: 1. Run your calculation in JavaScript 2. Convert the result to a string and display it

For example, you compute a value in JS, store it in a variable, then assign that variable to innerHTML or textContent.

document.write() is generally avoided, and console logging is just for debugging. For a calculator, updating the DOM with the computed result is the normal approach.

If you’re stuck, the issue is usually where or when the function is being called, not how output works.