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?

3
  • $(html).find("body").html(); ? Commented Feb 12, 2013 at 4:15
  • @aroth: That is also undefined. Commented Feb 12, 2013 at 4:18
  • Then I believe this is the explanation for why it is not working: stackoverflow.com/questions/2488839/…. Here's a demo; in Chrome everything is stripped except the two <p> tags. Commented Feb 12, 2013 at 4:24

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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/

1 Comment

Correct, except that it doesn't appear to be jQuery that is doing it. See stackoverflow.com/questions/2488839/…
0

You could try body[0].innerHTML()

1 Comment

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.
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>

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.