skip to Main Content

there is a problem with inserting html into js , when inserting indents are added and I don’t understand why. Building a simple calculator

for (var i = 0; i < num.length; i++) {
    num[i].addEventListener("click", function () {
        if (!operator) {

            console.log(this)
            num1 += this.textContent
            ny.push(num1)
            console.log(ny)
            result.innerHTML = num1;
        } else if (operator.length > 0) {

            num2 += this.textContent
            result.innerHTML = num2;
        }


    })

}

enter image description here

2

Answers


  1. I think this.textContent might contain spaces and/or enters.

    Instead of

    <div>
        textContent
    </div>
    

    try this

    <div>textContent</div>
    

    or try:

    this.textContent.trim().replace('t','')
    
    Login or Signup to reply.
  2. When using element.textContent you are getting the exact content from the source HTML, including whitespace in case the HTML isn’t minified.

    As an alternative, you can use element.innerText which gives the rendered text and does not normally include extra whitespace.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search