skip to Main Content
let counter = parseInt(document.getElementById("#integer").innerHTML)

let incbutton = document.querySelector("#increase")

incbutton.addEventListener("click", increase)

function increase() {
  counter += 1;
}
<h1 id="integer">100</h1>
<button id="increase">Increase</button>

when ı try to convert to integer content of h1 tag increase button is not working. ı think because of h1 tag still string not integer. what is the mistake here? your text

2

Answers


  1. simply update the counter value

    let counter = parseInt(document.getElementById("#integer").innerHTML)
    let incbutton = document.querySelector("#increase")
    incbutton.addEventListener("click", increase)
    function increase() {
      counter += 1;
      incbutton.innerHTML = counter;
    }
    
    Login or Signup to reply.
  2. The following code converts the content of the element with the ID integer to an integer:

    let counter = parseInt(document.getElementById("#integer").innerHTML);
    

    If the content of the element is not a valid integer, the parseInt() function will return NaN.

    function increase() {
      counter += 1;
    }
    

    To update the content of the element with the ID integer with the new value of the counter, you can use the innerHTML property:

    document.getElementById("#integer").innerHTML = counter;
    

    Here is a complete example of your code

    <!DOCTYPE html>
    <html>
    <head>
      <title>Counter</title>
    </head>
    <body>
      <h1><span id="integer">100</span></h1>
      <button id="increase">Increase</button>
    
      <script>
        let counter = parseInt(document.getElementById("integer").innerHTML);
    
        let incbutton = document.querySelector("#increase");
    
        incbutton.addEventListener("click", increase);
    
        function increase() {
          counter += 1;
          document.getElementById("integer").innerHTML = counter;
        }
      </script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search