简体   繁体   中英

Get DOM from a string

Given a String which contains HTML for an entire page, I want only the innerHTML of the body. Rather than parse the HTML myself, it seems easier if I could make an element from the String, and then just get the body directly.

I found some things related, but that I couldn't get to work (I can't find the question anymore).

xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
    var ret = xmlhttp.responseText + "";

    if(xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        alert(ret);
    }
}
xmlhttp.open("GET", "http://url.php", false);
xmlhttp.send();

Right now I have this ajax request, but I need only the body from the return.

I tried document.createElement(ret).body and new Element(ret).body but they didn't seem to work.

var helper = document.createElement("html");
helper.innerHTML = ret;         
body = helper.querySelector("body"); //Or getElementsByTagName("body")[0]

You could use simple_html_dom to do this, and get the HTML of the entire page using PHP, and then get only the contents of the body, like this

$html=file_get_html("url.php");
$body=$html->find("body");
$echo $body->plaintext

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