Xavier
Xavier

Reputation: 8362

remove element in jquery then append a new element?

I am trying to remove an span element from HTML then replace that element with a new span element.

View the fiddle for a working example: http://jsfiddle.net/DCJ9X/

<div id="foo">
    <span>FadeOut</span>
</div>

<input id="go" type="button" value="lets go!" />

$('#go').click(function() {

    $('#foo span').fadeOut(500, function() {
        $(this).remove().parent().append('<span>FadeIn</span>').fadeIn(500);
    });

});

As always I am grateful for your help stack!

Upvotes: 0

Views: 5618

Answers (3)

Tieson T.
Tieson T.

Reputation: 21236

Well, if'n you wanted to keep more or less what you have, this works:

$('#go').click(function() {

    var $foo = $('#foo');
    $foo.find('span').fadeOut(500, function() {
        $foo.remove('span').append('<span>FadeIn</span>').fadeIn(500);
    });

});

Upvotes: 1

Vince V.
Vince V.

Reputation: 3143

This should do the trick:

$('#foo span').fadeOut(500).replaceWith('<span>FadeIn</span>').hide().fadein(500);

Upvotes: 1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99919

Use .replaceWith() instead:

    var $span = $('<span>FadeIn</span>');
    $(this).replaceWith($span);
    $span.fadeIn(500);

http://jsfiddle.net/DCJ9X/4/

Or on one line:

$(this).replaceWidth($('<span>FadeIn</span>').fadeIn(500));

Upvotes: 4

Related Questions