September 26, 2011

How can I change the text of a <span> element?

Question by Sheehan Alam

I have a toggle button that I’m adding to an iFrame:

    $('#list div').each(function(){
        $(this).append('<span class="togglebutton">Maximize</span>');   

    $("span.togglebutton").click(function() {

How can I change the toggle between the text Maximize/Minimize when the toggleClass is maximized?

Answer by jondavidjohn

$("span.togglebutton").click(function() {
    var $this = $(this);  // cache jquerized 'this'

    var currentText = $this.text();

    // if the text is currently "Maximize"
    if (currentText === "Maximize") {
        // change it to new value
        $this.text("New Text");
    else {
        // change it back to "Maximize"

Answer by Starx

Well, if you are looking for some function like toogleClass() to do that job for you, you are out of luck. AFAIK, you have to do it manually.

Do something like this

function toggleText() {
    var curText = $("span.togglebutton").text();
    var newText;
    if(curText=="Maximize") { newText = "Minimize"; }
    else { newText = "Maximize"; }

Now you can call it happily where you want to toggle it. Like

    $("span.togglebutton").click(function() {

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!