How to target the replaced content after using `replaceWith`?

85 views Asked by At

I want to use Jquery (1.10.2) to replace some content on my site with the results of a API request. Then I want to execute some more javascript on that content. I know the new content is HTML, but I don't anything about it. Even if it has an #id, or ".class" assocated with it, thus I cannot target the content.

jQuery.replaceWith() will return the OLD "this"; How do I get the "this" for the new content?

http://jsfiddle.net/G24X8/3/

$('#fix').on('click', function() {
    $('#myStuff').replaceWith("<p>Hello new world!</p>"); // Hello new world content actually comes from a server
    // since replaceWith returns the old content, how do I get the $(?this?) for the new content, when I don't know what is in it?
});

-daniel

3

There are 3 answers

0
PSL On BEST ANSWER

You can just do this way to get hold of the newContent after adding it to DOM, if that is what you meant:

$('#fix').on('click', function() {
    var $newCont = $("<p>Hello new world!</p>");
    $('#myStuff').replaceWith($newCont); 
    //Do anything with $newCont
    //$newCont.css('color', 'blue');

});
1
Roy Tinker On

I suggest using .html() instead of .replaceWith() -- that way you're only replacing the contents of the target tag, not the tag itself.

$('#fix').on('click', function() {
    $('#myStuff').html("<p>Hello new world!</p>");
    //...
    $('#myStuff').doSomethingElse(); //whatever else you need to do
});
0
Ringo On

Try this:

$('#fix').on('click', function() {
    $('#myStuff').text('').html("<p>Hello new world!</p>");
});