How do I update a variable?

  • 0
    Doing something like a clicker on the web, the code below declares a variable. When pressed, it displays this variable and everything disappears; if you loop and put the button code in a function, it will display again and again (on the same page), but I need the variable to be updated as it is added.
    var money;
    function increment(){ money++; document.write(money) }
    document.write("<button onclick=increment>+1</button>");
    JavaScript Gavin Brady, Mar 26, 2020

  • 3 Answers
  • 0
    something like this

    var money=0;

    function increment(){
    money++;
    document.getElementById('money').textContent=money
    }

    document.write("<button onclick=increment()>+1</button>");
    document.write("<p id=\"money\"></p>");
    Anonymous

  • 0
    & lt; span id = "counter" & gt; & lt; span & gt;



    let money = 0;
    let counter = document.querySelector('#counter');
    function increment() {
    money++;
    counter.innerHTML = money;
    }

    document.write('<button onclick="increment()">+1</button>')
    Delilah Collier

  • 0
    The document.write call only works during page load. Calling it later will overwrite the existing content of the document.

    One way to solve the problem

    var button = document.createElement('button');
    button.innerHTML = 0;
    button.onclick = increment;
    document.body.append(button);

    function increment() {
    this.textContent = +this.textContent + 1;
    }
    Ethan Brandt

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!