How can I replace DOM node within memory using jQuery
I have the following code
$.getJSON("../services/getNavigationAffectedList.php", obj, function(response)
{
$.each(response, function(i, v)
{
// Get the old page source
var source = v;
//开发者_StackOverflow中文版 Get the updated preview HTML
var new_nav = $('#preview').find('#navigation-block').html();
// Replace the old navigation with the preview HTML
$(source).find('.navigation-block').html(new_nav);
var source = $(source).html();
var obj = {
page_path: i,
new_source: source
};
console.log(obj);
});
Which is attempting to replace the navigation-block class within the DOM contained in memory (source). Although, $(source).html() does not yield expected results.
Help?
Partial JSON response per David's request:
{"\/var\/www\/html\/cms\/sites\/about\/debbie.php":"\r\n ... tons more html here ....}
Here is a fiddle to test with: http://jsfiddle.net/eZP9E/1/
Try jQuery's replaceWith function. Is this what you're looking for?
http://api.jquery.com/replaceWith/
What is the un-desired result you are getting?
UPDATE: Turns out the problem is with the way it's creating the DOM elements in jQuery.
Your code expects the 'var original' is the element, but it isnt.
var container = $('<html><body><div class="navigation">1</div></body></html>');
alert(container.length); // returns 1, div.navigation
var container = $('<html><body><div class="navigation">1</div><div class="body"></div></body></html>');
alert(container.length); // returns 2, div.navigation, div.body
var container = $('<div id="root"><html><body><div class="navigation">1</div></body></html></div>');
alert(container.length); // returns 1, sweet! we can use this
After some testing, these are the results that I have from the code above.
The quick solution for your issue would be to update the code to something like this:
var original = $('<div id="root">' + v + '</div>', document);
精彩评论