Hardik Choudhary
Hardik Choudhary

Reputation: 3

How to give output of a java script variable in a button

I have a javascript variable "len" and I want its value in my button ,here is my button code :

<button type="button" class="btn btn-primary">
   Pending Task
   <span class="badge badge-light"></span>
   <span class="sr-only"></span> 
</button>

Upvotes: 0

Views: 53

Answers (1)

Sirko
Sirko

Reputation: 74046

In your case I suggest to add another <span> to make the text of your button addressable without changing the icons. So your button becomes

<button type="button" class="btn btn-primary">
   <span class="content">Pending Task</span>
   <span class="badge badge-light"></span>
   <span class="sr-only"></span> 
</button>

Then in your JavaScript, you need a selector to address this new <span>. Currently you button has no ID, so the following selector might also select other buttons. As you're already using bootstrap, you'll have jQuery available. That makes the code for setting the text rather short:

 $( 'nav button .content' ).text( len );

As you're just using vanilla JS right now, the above line could also be rewritten like this

 document.querySelector( 'nav button .content' ).textContent = len;

Upvotes: 1

Related Questions