Question

I tried to wrap a div after replace the original element from div to input but not work, could anyone suggest what wrong with my code below, thanks.

$('.sth').replaceWith(
    $('<input>', {
        value: $('.sth').text(),
        type: 'text'
    })
).wrap('<div class="new" />');

Demo: http://jsfiddle.net/zhmUK/1/

Was it helpful?

Solution

http://api.jquery.com/replaceWith/

Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.

$('.sth').replaceWith(
    $('<input>', {
        value: $('.sth').text(),
        type: 'text'
    }).wrap('<div class="new" />').parent()
);

OTHER TIPS

replaceWith returns your removed .sth element . Citation:

The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.

So you're wrapping the wrong element, element that is not in the DOM anymore.

From here: http://api.jquery.com/replaceWith/

you can try

$('.sth').wrap('<div class="new" />').replaceWith(
    $('<input>', {
        value: $('.sth').text(),
        type: 'text'
    })
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top