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

后端 未结 5 1783
青春惊慌失措
青春惊慌失措 2021-01-15 13:22

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


        
5条回答
  •  醉酒成梦
    2021-01-15 13:41

    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/

提交回复
热议问题