D. Krold D. Krold - 11 months ago 101
Javascript Question

Change the text of a Span

I want to change the text of a span upon button click.

Some other questions solve this by appending text but I don't want to keep the original text and rather substitute it completely.

My code looks like this now:

<button class="btn btn-primary" id="msgbtn">Messages <span id="mgsunread" class="badge badge-light">4</span></button>


And the JavaScript:

$('#msgbtn').on('click', function(event) {
span = document.getElementById("mgsunread");
txt = document.createTextNode("6");
span.appendChild(txt);
});


I would be grateful for any answer.

Answer Source

Since you are using jQuery, that would be simply

$('#msgbtn').on('click', function(event) {
  $("#mgsunread").text("6");
});

If you still want to stick to vanila javascript

document.getElementById("mgsunread").textContent="6";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download