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.

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

It isn't working for me. The span value was still 0.
How if, I am assigning an onclick="" to the button?
for that you need to declare a named function in your global namespace, and call it inside the button's onclick attribute, look at the edited answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.