Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change text on Twitter Bootstrap button whilst preserving icon?

How do I use javascript/jquery to change the text on a button in Twitter Bootstrap without destroying the icon?

So, this is my static markup:

<a class="btn" id="myButton" onclick="doSomething()"><i class="icon-ok"></i> Do it...</a>

I am able to change the icon, like this:

$('#myButton i:first-child').attr('class','icon icon-remove');

Which is fine, but for the love of all that is good I cannot find a way to set the button text without then wiping out the icon. Eg. if I do this:

$('#myButton').text('Some Remove Text');

I lose the icon element, so how can I access just the text and edit that, whilst preserving any child elements?

like image 646
Oliver Lloyd Avatar asked Apr 01 '12 13:04

Oliver Lloyd


1 Answers

You can wrap the content in a span element and then just find it in the context of your anchor.

$('#myButton span').text('Some Remove Text');

Also you can use $('#myButton i:first') instead of $('#myButton i:first-child') or even

$('#myButton i') or $('#myButton > i') which would be shorter.
like image 158
FreeCandies Avatar answered Oct 12 '22 17:10

FreeCandies