Link to home
Start Free TrialLog in
Avatar of CHINOS
CHINOS

asked on

jQuery body text replacement

Hello,

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();
    $('body').replaceWith(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,
   $('body').html().replaceWith($('body').html());  
but that will fail because replaceWith is not a function of html.

Method 2
    var html = $('body').parents().html();
    $('body').parents().replaceWith(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').replaceWith($(this).parents().html())
    });

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

My body code is here...

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


Any ideas?  
ASKER CERTIFIED SOLUTION
Avatar of ncoo
ncoo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
How about just wrapping your html tag in <body> a body string:

                  var html = "<body>" + $("body").html() + "</body>"
                  $("body").replaceWith(html)
Avatar of CHINOS
CHINOS

ASKER

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.