Skip to content Skip to sidebar Skip to footer

How To Remove Whole Html, Head Tags And Body Tag From String With Html Using Javascript?

I have a template file that is called myWebsite.html. It contains everything that HTML template needs to have. So it has HTML, HEAD and BODY tags. I want to load it with JavaScript

Solution 1:

Why not fetch the information out of the tag and then work with that? There is no need to fetch all information and the removing html, head and body:

content = $val.getElementsByTagName('body')[0].innerHTML();

Solution 2:

You could extract it with a regex. Something like: /\<body[^>]*\>(.*)\<\/body/m - that should return all content within the <BODY> element.

$val = getData('myWebsite.html');
var reg = /\<body[^>]*\>([^]*)\<\/body/m;
div.innerHTML = $val.match( reg )[1];

Example jsFiddle code: http://jsfiddle.net/x4hPZ/1/

Solution 3:

With jQuery you could do it like this:

$(document).ready(function(){
    var your_content = $("html").clone().find("head,body").remove().end().html();
});
  1. get the content with "html" selector
  2. make a copy with clone
  3. find the tags you want to remove
  4. remove them and
  5. convert back to HTML

all in one line.

HTH,

--hennson

Solution 4:

how about:

var bodyContents = htmlstring.split('<body');//no >, body could have a property
bodyContents = bodyContents[1].replace('</body>','').replace('</html>','').replace(/^.*\>/,'');

The last regex replace removes the closing > of the opening body tag, and all possible tag properties.

This is, however, not the way I would do things... If at all possible, I'd create an (i)Frame node, load the html into that frame, and get the innerHTML from the body tag. Just a suggestion.

Right, the iFrame way:

vardocument.ifrm = document.createElement('iframe')
document.ifrm.style = 'visibility:hidden';
document.body.appendChild(document.ifrm);
idoc = (document.ifrm.contentDocument ? document.ifrm.contentDocument : document.ifrm.contentWindow.document;)
idoc.open();
idoc.writeln('<html><head><title>foobar</title></head><body><p>Content</p></body></html>');
idoc.close();
var bodyContents = idoc.body.innerHTML;

For code explanation: http://softwareas.com/injecting-html-into-an-iframe

or any other hit on google.com for that matter :)

Post a Comment for "How To Remove Whole Html, Head Tags And Body Tag From String With Html Using Javascript?"