We help IT Professionals succeed at work.

jQuery body text replacement

CHINOS asked

I need to capture all of the text of the body and replace it after I have ran it against a reg expression.  

I have tried the following ways already (these are without the expression applied, just trying for basic html replacement here)....

Method 1
    var html = $('body').html();

### the problem with this method is it doens't return the <body> tags when it replaces it since the jQuery replaceWith function actually deletes the code it finds, I've also tried manually inserting the tags into the parameters of the function but it doenst work.  

The way to fix it would seem something like this,
but that will fail because replaceWith is not a function of html.

Method 2
    var html = $('body').parents().html();

### the problem with this method is it includes everything in the head also, so obviously it fails when it tried to include the head twice.  

Method 3
    $('body').children().each(function() {

### this doesnt work either, here I'm trying to find the html by going from the child node...

My body code is here...

    <h1>my header</h1>
    <div id="wrapper">
    <div class="col1">
        <div id="ref">
            <p>some text</p>

Any ideas?  
Watch Question

You should just be able to do the following:
var html = $('body').html();

Open in new window

How about just wrapping your html tag in <body> a body string:

                  var html = "<body>" + $("body").html() + "</body>"


wow, i can't believe I missed that, I had tried that from the console but it returned jQuery(body) and not the text so I mistakenly assumed it wasn't working and went on to try other things.  

also realized replaceWith was not suitable in the first place

The .replaceWith() method returns a jQuery set containing only a paragraph.