So I want to add to a variable every time someone clicks a button on my website. I am very new to HMTL so I don't know how to do this. All the examples I've googled just change text into other text and not adding to a variable.
If someone would like to enlighten me on how to do this I would greatly apricate it.
function changeIt() {
document.getElementById('test').innerHTML = "<h2>Congrats</h2>";
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
CodePudding user response:
var sum = 0;
function changeIt() {
sum ;
document.getElementById('test').innerHTML = `<h2> ${sum} </h2>`;
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
CodePudding user response:
The code you've written in document.innerHTML
is correct. For making it dynamic and to add a new Congrats
onto the screen instead of just modifying the old one, you need to keep a global counter and loop over it.
let count = 0;
function changeIt() {
count ;
for (let i=0;i<count;i ) {
document.getElementById('test').innerHTML = '';
let h2 = document.getElementById('test').createElement;
h2.innerHTML = "Congrats";
document.getElementById('test').appendChild(h2);
}
}
Since you are calling the changeIt
function on every button click it will let you update the count and will loop over the count to add the Congrats
'count' number of times to your div.
Hope this is clear and helps :)