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

后端 未结 5 1700
青春惊慌失措
青春惊慌失措 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:27

    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

    0 讨论(0)
  • 2021-01-15 13:33

    may be this can help you

    var head = jQuery('<div/>').append(htmlString).find('head').html();
    
    var body = jQuery('<div/>').append(htmlString).find('body').html();
    
    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2021-01-15 13:42

    Try Below Code:

    var head = htmlString.match(/<head[^>]*>[\s\S]*<\/head>/gi);
    var body = htmlString.match(/<body[^>]*>[\s\S]*<\/body>/gi);
    
    0 讨论(0)
  • 2021-01-15 13:48

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

    0 讨论(0)
提交回复
热议问题