0

I am trying to unwrap the contents of an html document string. I'm being given back a full html document from the froala rich text editor, that includes a head, title, and body tag which I want to remove.

The problem is that any selector I try gives me back an array that has a HTMLTitleElement, and then an array item for each root element in the document contents.

So, for example:

$('<!DOCTYPE html><html><head><title></title></head><body><h2>Summary</h2><div>Some content here</div></body></html>');

gives me back an array that has 3 elements: HTMLTitleElement, HTMLHeadingElement, HTMLDivElement.

I was hoping for a single HTMLBodyElement, or something that I could call .html() on, in order to get the content entered into the editor without all the other html document wrappers.

j08691
  • 204,283
  • 31
  • 260
  • 272
Brian
  • 325
  • 2
  • 10
  • 2
    Well, you need to select the element you want. So use the code you have, then do `.find('body')` on that. – Heretic Monkey Jun 08 '17 at 22:16
  • Forgot to mention the things I tried, but that was one of them. That query results in no matches. Thanks for the suggestion. – Brian Jun 08 '17 at 22:20
  • Possible duplicate of [Parse a HTML String with JS](https://stackoverflow.com/questions/10585029/parse-a-html-string-with-js). I'm rather partial to [this answer](https://stackoverflow.com/a/21870431/215552) myself. – Heretic Monkey Jun 08 '17 at 22:29
  • Close enough. When I do a .html() on the result of all that it still includes "", but I can strip that out. Thanks. – Brian Jun 08 '17 at 23:38

2 Answers2

0

You can use regular expression to get body content.

var htmlContent = "<!DOCTYPE html><html><head><title></title></head><body><h2>Summary</h2><div>Some content here</div></body></html>";

var bodyContent= /<body.*?>([\s\S]*)<\/body>/.exec(htmlContent)[1];
  • Not sure if I missed a step in there, but for me plainText resulted in: "$(' Summary Some content here ')" I was looking for "

    Summary

    Some content here
    "
    – Brian Jun 09 '17 at 01:35
0

For my specific situation, I found this produced what I was looking for:

$('body', $('#editor-container iframe').contents()).html()
Brian
  • 325
  • 2
  • 10