Reputation: 7172
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?
$('#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
Upvotes: 1
Views: 103
Reputation: 3965
Try this:
$('#fix').on('click', function() {
$('#myStuff').text('').html("<p>Hello new world!</p>");
});
Upvotes: 0
Reputation: 123739
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');
});
Upvotes: 2
Reputation: 10152
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
});
Upvotes: 1