Shai UI
Shai UI

Reputation: 51968

Replace Body but not Script within it?

<body>
   <div>blabla</div>
   <div>blabla2</div>
   <script>
      ....
   </script>
</body>

I 'd like to replace all the content of body but leave the script tag and contents within the script tag untouched.

If I do $('body').html('<span>hello</span>') it'll replace the entire content so it'll look like:

<body>
  <span>hello</span>
</body>

But what I'd like is for it to look like:

<body>
  <span>hello</span>
  <script>...</script>
</body>

Basically replace everything inside body EXCEPT script. is this possible?

Upvotes: 1

Views: 1091

Answers (6)

Tomalak
Tomalak

Reputation: 338326

$("body").contents().not("script").remove();
$("<div>Test!</div>").prependTo("body");

Docs: contents(), prependTo().

This assumes scripts are children of the body. If they could be nested deeper, execute this first:

$("body * script").appendTo("body");

Upvotes: 1

T J
T J

Reputation: 43166

You can use the remove() method with :not() selector like

$(document.body).find(':not(script)').remove();
// body is clear. do whatever you want.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  var test1;
</script>
<span>hello</span>
<script>
  var test2;
</script>
<p>how<span>are</span>
</p><span>you</span>

Upvotes: 0

monterico
monterico

Reputation: 380

Try with this code:

$('body').html('<span>hello</span><script>'+$('body script').html()+'</script>');

Upvotes: 1

Jack jdeoel
Jack jdeoel

Reputation: 4584

Just find div and remove....

$('body').prepend('<span>hello</span>').find("div").remove();

Upvotes: 0

Gaurav Aggarwal
Gaurav Aggarwal

Reputation: 10197

If you replace the whole html in body obviously it will remove each and every thing from it.

The best way is define the script in separate variable and then replace the body after that just append that variable in body

var scriptHtml = $('body').find('script');
$('body').html('<span>hello</span>');
$('body').append(scriptHtml);

Upvotes: 1

JohannesB
JohannesB

Reputation: 2015

If you know that your script is the last script in the body element (which is usually the case) you could do it like this:

$("body *:not(script:last)").remove();
$("body").prepend($("<div>Test!</div>"));

Fiddle: https://jsfiddle.net/cq43bvam/1/

Upvotes: 3

Related Questions