0

Given

var html = "<html><body><p>Hello, World!</p><p>Ciao!</p></body></html>";

I would like to extract the inner HTML of the body tag (<p>Hello, World!</p><p>Ciao!</p>).

.find() finds the body DOM node

var body = $(html).find("body");

but I cannot find a means to get the inner HTML of that node. I tried:

var text = body.text(); //  returns ""
var var = body.var(); // returns undefined

How can I get a string representation of the <body> tag's inner HTML?

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • `$(html).find("body").html();` ? – aroth Feb 12 '13 at 04:15
  • @aroth: That is also `undefined`. – Eric J. Feb 12 '13 at 04:18
  • Then I believe this is the explanation for why it is not working: http://stackoverflow.com/questions/2488839/does-jquery-strip-some-html-elements-from-a-string-when-using-html. Here's a [demo](http://jsfiddle.net/aNh6a/); in Chrome everything is stripped except the two `

    ` tags.

    – aroth Feb 12 '13 at 04:24

4 Answers4

1

You could use substring, get the index of and the index of and make a substring with what is inside.

var bot = html.indexOf("<body>");
var top= html.indexOf("</body>");
var body=html.substring(bot,top);
Luis Tellez
  • 2,785
  • 1
  • 20
  • 28
0

jQuery will strip the html and body tags out when you wrap the string in $().

Therefore you can do this:

var str=$('<div>').append($(html)).html()

DEMO http://jsfiddle.net/LxdrM/

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Correct, except that it doesn't appear to be jQuery that is doing it. See http://stackoverflow.com/questions/2488839/does-jquery-strip-some-html-elements-from-a-string-when-using-html – aroth Feb 12 '13 at 04:27
0

You could try body[0].innerHTML()

  • var body = $(html).find("body"); will return an array of elements. Use body[0] to get the element and call the innerHTML function on it. – user2049150 Feb 12 '13 at 04:31
0

As you want to show the string representation, it will be better to keep the html in a div element (or any other element inside the body tag) instead of body tag itself. For string representation, use TextArea which is what also SO is using.

Working fiddle

$(function(){
   var body = $('html').find('div'); 
   var text = body.html(); 
   $("#textArea").val(text);
});

HTML

<html>
     <body>
        <div><p>Hello, World!</p>
             <p>Ciao!</p>
        </div>
        <textarea id="textArea" name="post-text" cols="92" rows="15" tabindex="101">
        </textarea>
     </body>    
 </html>
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • Unfortunately I have no control over the HTML fragment. It does not have a single tag that contains the rest of the tags inside the body. – Eric J. Feb 12 '13 at 18:07