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:

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

    $("span.togglebutton").click(function() {
        $(this).closest("li").children("div").toggleClass("maximized");
    });
</script>

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'
    $this.closest("li").children("div").toggleClass("maximized");

    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"
        $this.text("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"; }
    $("span.togglebutton").text(newText);
}

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

    $("span.togglebutton").click(function() {
        $(this).closest("li").children("div").toggleClass("maximized");
        toggleText();
    });

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!