0

When assigning the add(a, b) function to the displayText Variable it won't work when written as the comment on the last line below.

I assume it is because I am simply assigning the displayText variable a new value. Or?

How do I get around that issue?

var displayText = document.getElementById("display-text").innerHTML

function operate(operator, a, b) {
    if (operator === '+') {
        document.getElementById("display-text").innerHTML = add(a, b)
        // displayText = add(a, b)
  • You get a reference to the *element*, not a property of the element: `const tmp = document.getElementById('xxx'); tmp.innerHTML = add(a, b)` – Dave Newton Mar 11 '21 at 20:39
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+innerHTML+stored+in+variable+doesn’t+change) of [Setting innerHTML: Why won't it update the DOM?](https://stackoverflow.com/q/8196240/4642212). – Sebastian Simon Mar 11 '21 at 21:46

2 Answers2

0

This line:

var displayText = document.getElementById("display-text").innerHTML

Is only getting a copy of the innerHTML stored in the variable, not a reference to the element's innerHTML property. So when you set the variable later, your only overriding the string in the variable, not the property of the element.

You need the line to be:

document.getElementById("display-text").innerHTML = add(a, b);

So that you can be setting the property.

NOTES:

  • Now, you really shouldn't be using innerHTML when you can avoid it because it has security and performance implications. If there isn't any HTML in the string, you definitely shouldn't be using it and instead you should be using .textContent.

  • In order to not have to scan the DOM over and over for the same element, it makes sense to find it once and get a reference to the element. That way, you can access the variable holding a reference to the element as often as you need to. This is what you were attempting to do with the property, but the property stores a string, whereas the element is an object.

      // Get a reference to the element, not properties of the element
      var displayText = document.getElementById("display-text"); 
    
      function operate(operator, a, b) {
        if (operator === '+') {
            // Now you can reference the element without searching for it again
            displayText.textContent = add(a, b)
    

This is also the better approach because now you can access the element variable and get any property of the element you want without having to scan for the element again:

displayText.textContent = "foo";
displayText.classList.add("foo)";
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

You might want to refactor your code to something like this

let displayText = document.getElementById("display-text")

function operate(operator, a, b) {
    if (operator === '+') {
        displayText.innerHTML = add(a,b)

You don't need to grab the element from your function every-time your function executes