TextContent

At this point, if the calculator shows 0 (the default number), the target number should replace zero. If the calculator shows a non-zero number, the target number should be appended to the displayed number

Here, we need to know two things:

  • The number of the key that was clicked

  • The current displayed number

We can get these two values through the textContent property of the clicked key and .calculator__display , respectively.

Edit your js file like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// .. some code from previ
const display = document.querySelector('.calculator__display') // add this plus the highlighted
keys.addEventListener('click', e => {
  if (e.target.matches('button')) {
    const key = e.target
    const action = key.dataset.action
    const keyContent = key.textContent
    const displayedNum = display.textContent
    // ...some of code from previous update are below
  }
})

If the calculator shows 0, we want to replace the calculator’s display with the clicked key. We can do so by replacing the display’s textContent property.

The textContent property sets or returns the text content of the specified node, and all its descendants.

If you set the textContent property, any child nodes are removed and replaced by a single Text node containing the specified string.

Remember dom is heirachy based

To make use of this let us edit our js file like so:

add this the below, just below the previous update just the comment // ...some of code from previous update are below

1
2
3
4
5
if (!action) {
  if (displayedNum === '0') {
    display.textContent = keyContent
  }
}