开发者

Parse complete html page with jquery

开发者 https://www.devze.com 2023-01-30 21:22 出处:网络
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 complet开发者_Go百科e page including doctype, head elements and body

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 complet开发者_Go百科e 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;


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


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


function ajaxLoadContent(element) {
$.ajax({
    url: "url to the page",
    type: "GET",
    timeout: 5000,
    datattype: "html",
    success: function(data) {
     var result = $(data);
    },
});
return false;

You should now be able to call the result like this (remember it's not added to the DOM yet):

alert(result.html());

Add to the DOM

result.appendTo("body");

Let me know if this works for you.


Try the load method of jQuery object: http://api.jquery.com/load/

Load data from the server and place the returned HTML into the matched element.

0

精彩评论

暂无评论...
验证码 换一张
取 消