0

I have an html with a span like this:

<span class="className">0</span> and it should display: 0

The problem is, how could I add a value (e.g. when value is 2, it will become 3) to the span by clicking a button and by doing it using javascript.

Lloyd Dominic
  • 778
  • 8
  • 25

1 Answers1

2

You can modify the content of any HTMLElement using:

look at this snippet:

document.addEventListener("DOMContentLoaded", function(){
   var button = document.querySelector("#mybutton");
   var span = document.querySelector(".className");
  
   button.onclick = function() {
     span.textContent= parseInt(span.textContent, 10) + 1;
   }
  
});
<span class="className">0</span>
<button id="mybutton">add</button>

EDIT: If you want to use onclick="" which I don't recommend, you could do something like this:

var myFunction = function() {
   var span = document.querySelector(".className");  
   span.textContent= parseInt(span.textContent, 10) + 1;  
}
<span class="className">0</span>
<button id="mybutton" onclick="myFunction()">add</button>
Community
  • 1
  • 1
Santiago Hernández
  • 5,438
  • 2
  • 26
  • 34