jQuery: Manipulating an Ajax response before inserting it into the DOM
Quick gotcha - well it got me anyway. I was manipulating an HTML response from an Ajax request with jQuery before inserting it into the DOM but my changes were not making it into the DOM. My code looked something like this simplified example:
$.get('/some-url/', function(data)
{
$(data).find('#someDiv').append('<p>Some Text</p>');
$('body').append($(data));
});
The problem is is that whilst the jQuery object is manipulated the data variable itself is not, so when inserting $(data) into the DOM the changes were lost as a fresh jQuery object created with the unmodified variable was inserted. The following preserves the changes:
$.get('/some-url/', function(data)
{
var $data = $(data);
$data.find('#someDiv').append('<p>Some Text</p>');
$('body').append($data);
});
This works as it is the same jQuery that is modified and inserted into the DOM.