Search code examples
javascriptjqueryclonereplacewithjquery-2.0

.replaceWith() is not working in jQuery 1.9+


I'm trying to clone a <textarea> and clone and replace the digit in the label <label> Number 1 <label> increasing by 1 each time the add button is pressed (So the first label will have Number 1, the label underneath Number 2 etc).

This works with jQuery 1.8 and below but anything above does not clone and add 1 to the digit.

HTML

<div>
 <label for="number">Number <span class="one">1</span></label>
 <textarea id="number"></textarea>
</div>
<button>Add</button>

jQuery

var $row = $('div').clone(),
    cloneCount = 2;

$('button').click(function () {
    $row.clone().insertBefore($("button"));
    $('span').clone().attr('span', cloneCount++).replaceWith($('[class=one]:last')).text(cloneCount - 1);
});

JSFIDDLE: http://jsfiddle.net/wba6jvkj/


Solution

  • I don't know what you were attempting with .attr('span' and why it seemed to work in < 1.8, or why you are subtracting one from cloneCount, but this should do what you want:

    var $row = $('div').clone(),
        cloneCount = 2;
    
    $('button').click(function () {
        $row.clone().insertBefore($("button"));
        $('span.one:last').text(cloneCount++);
    });
    

    jsFiddle example