Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse complete html page with jquery

I load a html with ajax. I want to load the result in a jquery object. I tried that but it returns null. How can I do this? I got a complete page including doctype, head elements and body elements.

var test = $(result); //result contains html code
alert(test.html()); //returns null

I load the data with this function.

function ajaxLoadContent(element) {
    $.ajax({
        url: "url to the page",
        type: "GET",
        timeout: 5000,
        datattype: "html",
        success: function(result) {
        //handler
        },
    });
    return false;
like image 977
Mark Baijens Avatar asked Dec 13 '10 14:12

Mark Baijens


2 Answers

It's a while ago, but maybe you're still interested in it..

The intern implementation of $(String) is not able to build an jQuery object that contains head or body tags. It will simply ignore them and move all elements inside on level up.

So if your string is for example

<html>
  <head>
    <meta ...>
  </head>
  <body>
    <div id="a"/>
  </body>
</html>

the resulting jQuery object will be an array of two elements

[<meta ...>, <div id="a" />]

to get a body-like jQuery object cut everything but the body content before passing it to jQuery:

body = '<div id="body-mock">' + html.replace(/^[\s\S]*<body.*?>|<\/body>[\s\S]*$/ig, '') + '</div>';
var $body = $(body);

now things work as expected.. for example

$body.find('#a')

Hope that helps..

like image 69
lrsjng Avatar answered Sep 19 '22 04:09

lrsjng


test is just an html string, so you could simply do this to show the contents

alert(result);

and if you want to bind that to an element

$("#myDiv").html(result);
like image 45
hunter Avatar answered Sep 21 '22 04:09

hunter