- How to select and replace the whole page with jQuery
- 5 Answers 5
- .replaceWith()
- version added: 1.2 .replaceWith( newContent )
- version added: 1.4 .replaceWith( function )
- Additional Notes:
- Examples:
- How do I replace the entire HTML node using jQuery
- 5 Answers 5
- Replace text in HTML page with jQuery
- 7 Answers 7
- Replace entire HTML document in-place
- 2 Answers 2
How to select and replace the whole page with jQuery
My design of a page forces me to refresh the whole page with html that I have loaded via ajax. $(‘html’).replaceWith(data); Gives me errors. Any ideas?
Won’t the html tag contain the script that is doing the replacing? If you’re using the body tag make sure your html fits.
5 Answers 5
I had the same issue, but this didn’t help. If you need to also replace the tag (so, the whole page), you can also do
I know this an old question, but for future references, this works, but you have to understand that it might leave the old DOM script handlers and result in memory leaks.
Although this will not replace the head section, which might be required to load the necessary Javascript and CSS files necessary to render the page properly.
Actually, jQuery does do the work of execute any embedded javascript. CSS stylesheets will absolutely be applied. Just realize that the CSS stylesheets you’ve removed remain in the rulesets, they don’t get removed.
this might be the solution you’ll require, It replaces the entire document including its head. You won’t have any issues loading your new css, js & other resources. I’ve assumed you receive the new html content by invoking a REST api:
giving me some weird css problems, but this worked fine:
Strange behavior by jQuery.replaceWith and jQuery.html when executed with ‘body’ selector. You loose the body tag after the call:
It doesn’t happen with any other selector as:
$('title').replaceWith('');
Also jQuery.html doesn’t double the body tag (as it does with other tags), and operates like replaceWith when called like this:
I hope this isn’t a grey zone of jQuery. Or if it is, they don’t think to fix it. I have applications where I use $(‘body’).html when $(‘body’).replaceWith should be used.
.replaceWith()
Description: Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
version added: 1.2 .replaceWith( newContent )
version added: 1.4 .replaceWith( function )
The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call. Consider this DOM structure:
div class="container">
div class="inner first">Hello div>
div class="inner second">And div>
div class="inner third">Goodbye div>
div>
The second inner could be replaced with the specified HTML:
$( "div.second" ).replaceWith( "
New heading
" );
This results in the structure:
div class="container">
div class="inner first">Hello div>
h2>New heading h2>
div class="inner third">Goodbye div>
div>
All inner elements could be targeted at once:
$( "div.inner" ).replaceWith( "
New heading
" );
This causes all of them to be replaced:
div class="container">
h2>New heading h2>
h2>New heading h2>
h2>New heading h2>
div>
An element could also be selected as the replacement:
$( "div.third" ).replaceWith( $( ".first" ) );
This results in the DOM structure:
div class="container">
div class="inner second">And div>
div class="inner first">Hello div>
div>
This example demonstrates that the selected element replaces the target by being moved from its old location, not by being cloned.
The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.
Additional Notes:
- The .replaceWith() method removes all data and event handlers associated with the removed nodes.
- Prior to jQuery 1.9, .replaceWith() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. The method might or might not have returned a new result depending on the number or connectedness of its arguments! As of jQuery 1.9, .after() , .before() , and .replaceWith() always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect—that is, neither the set nor the nodes it contains are changed.
Examples:
On click, replace the button with a div containing the same word.
How do I replace the entire HTML node using jQuery
I get this string returned as a result to an AJAX request. I would like the browser to render and display that string. The idea would be to do something like:
Well, that doesn’t work. I’ve attempted to use an IFRAME but I haven’t figured out how to get that to work either. Note: It is impossible for me to change this string. It is also impossible for me to regenerate this string in a subsequent call to the server (otherwise I could just redirect the browser to that url).
As far as I’m aware there’s no parent for the html element, IE6 and IE7 excepted. (But they hardly count) So you need to look at operations which work directly on $(‘html’) — outerhtml sounds about right.
5 Answers 5
The document.open/write/close methods will do what you want:
var newDoc = document.open("text/html", "replace"); newDoc.write(myString); newDoc.close();
Unless you pass in the replace parameter, the document.open call adds page history. So users would have to click back twice to go to the previous page.
Thanks, this works perfectly. Do you happen to know if this behaves differently in any non-ie browsers?
Since these have been part of the DOM for a very long time, I’d expect them to work correctly across all modern browsers.
Hey, currently there is a problem with firefox and hard refresh when using solution. Is there a workaround nowadays?
This solution works for me in W7/MF, but when executing statement newDoc.write(myString) I receive Permission denied error in W7/IE with error number number -2146828218.
You could just strip out the html tags, and then put everything inside the html element:
$('html').html(myString.replace(/(.*)/, "$1"));
Thanks but this doesn’t work. No matter what value I try, the result of $(‘html’).html(somevalue) is a blank page with an empty DOM (in IE).
At least in firefox(47.0) the solution:
var newDoc = document.open("text/html", "replace"); newDoc.write(response); newDoc.close();
does not work as suggested since pressing the back button on firefox still loads the previous history entry — i.e. the entire point of using «replace» is to avoid having users click their back button only to be greeted by the view of the page before the last time the document.write() was called. The way of doing this that does not cause the aforementioned effect is simply calling methods on the document object directly:
document.open("text/html", "replace"); document.write(response); document.close();
Using the replace option not only avoids filling the users history with garbage, but also helps in dealing with the issues that arise from the weird ways in which browsers often handle the history entries created by javascript, as sometimes allowing the browser to log the changes made to the document by javascript in history might have unexpected results when handling the back/forward operations (for instance adding ‘wyciwyg://(somenumber)’ to the url after performing a document.write() on the document that had its history reverted to a previous state).
Replace text in HTML page with jQuery
How do I replace any string in jQuery? Let’s say I have a string «-9o0-9909» and I want to replace it with another string.
possible duplicate of How to replace a block of HTML with another block of HTML using jQuery before asking a question, it is good to check out the automated suggestions the system makes when entering a question title
can you elaborate please on why you think jquery is the way to go — the answers so far might be off track.
I can change the text in c# page, javascript and database and html pages, but I was thinking if it’s possible to achieve that using jquery after page load. I am trying to save sometime and learn something new 🙂
7 Answers 7
You could use the following to replace the first occurrence of a word within the body of the page:
var replaced = $("body").html().replace('-9o0-9909','The new string'); $("body").html(replaced);
If you wanted to replace all occurrences of a word, you need to use regex and declare it global /g :
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string'); $("body").html(replaced);
If you wanted a one liner:
$("body").html($("body").html().replace(/12345-6789/g,'abcde-fghi'));
You are basically taking all of the HTML within the tags of the page into a string variable, using replace() to find and change the first occurrence of the found string with a new string. Or if you want to find and replace all occurrences of the string introduce a little regex to the mix.
See a demo here — look at the HTML top left to see the original text, the jQuery below, and the output to the bottom right.
Replace entire HTML document in-place
I’m trying to avoid using a data URI because I do not want the generated document to be stored in the browser’s history. Is it possible to replace the entire HTML document in-place? I tried jQuery(«html»).html(«. «) , but the style information does not survive.
I’m confused by your statement «style information does not survive», the styles will be linked to, or included in the document, so if you replace the whole document you would expect the styles to get lost? Do you really need to replace the /whole/ document? What are you trying to achieve from the visitors point of view?
I didn’t realize you were talking about new style info. That comment got me wondering; I’ve updated my answer a bit.
2 Answers 2
You probably want to do this:
jQuery("body").html("new content");
. where «new content» would ideally only include the markup that would normally appear within the body element and not the rest. That will replace the body element’s contents, whilst leaving anything you have in head (like style sheet information) alone. If you also want to update the title, you can do that via document.title = «new title»;
Edit I got to wondering about replacing everything inside the html element, whether that would work, and what would happen. So I did this:
body Note now this text current appears in a sans-serif, bold, blue font.
And the results were quite interesting — I end up with a DOM structure that doesn’t have a head or body at all, just html with the descendants of head and body inside. This is probably what’s messing up the (new) styling in the new content. I get essentially the same result setting innerHTML directly (which may be why it doesn’t work in jQuery; jQuery uses innerHTML when it can, although it’s very sophisticated about not doing so when it can’t); whereas if I do something similar by explicitly creating the head and body elements via document.createElement and document.appendChild , it works.
All of which almost certainly means this is more effort than it’s worth.
But: Note that changing the content of the head and body elements seems to work just fine:
body Note now this text current appears in a sans-serif, bold, blue font.
So if you separate the «page» you’re loading into head and body parts, you can easily update it in place.