Search code examples
jqueryappendcloneaddclass

Cloning, appending and modifying (frogs)


In the jQuery example below, before showing a cloned segment of HTML, how do I change the text "Remove Frog" to "Remove Frog #99" and also add an id called "frog99", where 99 is a sequencing number?

    <div id='imageBox'>
    </div>

    <div class="hidden" id='template'>
        <span class='alignRight'><a href='#' class='deleteFrog'>Remove Frog</a></span>
        <span class='alignRight'><a href='#' class='addFrog'>Add Frog</a></span>
        <img src="img/frog.jpg">
    </div>

Script:

var frogCount = 0;

$(document).ready(function() {
    // listener: add "live" listener to link
    $("#addFrog").live('click', function() {
        // Clone hidden template
        myClone = $("#template").clone();
        // Before showing cloned object, I would like to change text "Remove Frog" to "Remove Frog #99".
        // I think it should look something like this,
        myClone.("a").text("Remove Frog #" + ++frogCount);

        // Also add an id called "frog99", where 99 is a sequential number.

        myClone.removeClass("hidden");
        $('#imageBox').append(myClone);
    });
});

Solution

  • Change the line

    myClone.("a").text("Remove Frog #" + ++frogCount);
    

    to

    myClone.find("a.deleteFrog")
        .text("Remove Frog #" + ++frogCount)
        .attr('id','frog'+frogCount);