简体   繁体   中英

How to get head and body tags as a string from html string?

Hey i have an html string i'm having trouble getting the tags from.

I have tried alot of stuff, here are some :

var head = $("head",$(htmlString)).html();
var body = $("body",$(htmlString)).html();
var head = $("head",htmlString).html();
var body = $("body",htmlString).html();
var head = $("head",$(htmlString).html()).html();
var body = $("body",$(htmlString).html()).html();
var head = htmlString.match(/<head[^>]*>([^<]+)<\/head>/);
var body = htmlString.match(/<body[^>]*>([^<]+)<\/body>/);
var head = jQuery('<div/>').append(htmlString).find('head').html();
var body = jQuery('<div/>').append(htmlString).find('body').html();

Any many other tries besides that. All of this return "undefined" or "" or jquery object when i try loging it to console.

Could anyone tell me how can i get the body and head tags as a string?

Prefered with jQuery/JS and not regex

Try Below Code:

var head = htmlString.match(/<head[^>]*>[\s\S]*<\/head>/gi);
var body = htmlString.match(/<body[^>]*>[\s\S]*<\/body>/gi);

Since you have well formed HTML, you can create a document and select nodes from it:

var doc = (new DOMParser()).parseFromString(htmlstring,"text/html");
console.log(doc.head.outerHTML);
console.log(doc.body.outerHTML);

Here is a demonstration: http://jsfiddle.net/X3Uq2/

In Chrome, you can't use a "text/html" content type, so you have to make an XML document and use getElementsByTagName :

var s = new XMLSerializer();
var doc = (new DOMParser()).parseFromString(data,"text/xml");
console.log(s.serializeToString(doc.getElementsByTagName("head")[0]));
console.log(s.serializeToString(doc.getElementsByTagName("body")[0]));

http://jsfiddle.net/X3Uq2/2/

You can use javascript slice method this way:

 var html = '<!DOCTYPE html>'+ '<html>'+ '<head>' + '<meta name="viewport" content="width=device-width" /> '+ '<title></title>' + '</head>' + '<body>Some Text!</body>' + '</html>' var bEnd, bStart; bStart = html.indexOf("<body"); bEnd = html.indexOf("</body"); var body = html.slice(bStart, bEnd); console.log(body);

may be this can help you

var head = jQuery('<div/>').append(htmlString).find('head').html();

var body = jQuery('<div/>').append(htmlString).find('body').html();

It's really simple:

JQuery: $(head)
Native js: document.head

If you wanted to get html of this tag:

In JQuery: $(head).html();
Native js: document.head.innerHtml

You find nice JQuery refernece here: http://visualjquery.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM