Example of Changing Output with a Button in JavaScript
Showcase
0
This example starts with a number at 0, increases the number by 1 each time the + button is pressed, and decreases the number by 1 each time the - button is pressed.
Code
HTML
<input type='button' onclick='count("+")' value='+'/>
<input type='button' onclick='count("-")' value='-'/>
<div id='result'>0</div>
- Displays the initialized number in
<div id='result'>0</div>
. - Determines which action will be executed by giving different arguments to
onclick='count()
according to the button.
JavaScript
<script>
const resultElement = document.getElementById('result');
let counter = resultElement.innerText;
function count(type) {
if(type === '+') {
counter = parseInt(counter) + 1;
} else if(type === '-') {
counter = parseInt(counter) - 1;
}
resultElement.innerText = counter;
}
</script>
- Uses
document.getElementById('result')
to readid='result'
from<div id='result'>0</div>
and keeps it as a DOM object. - Reads the internal string through
let counter = resultElement.innerText
. - Parses the string into an integer using
parseInt(counter)
. - Changes the internal string using
resultElement.innerText = counter
.