开发者

Is there a way to use the jQuery selector to get the same string as returned by document.documentElement.outerHTML?

开发者 https://www.devze.com 2023-02-11 14:10 出处:网络
I was wondering if there is an alternative to using the Javascript: document.documentElement.outerHTML

I was wondering if there is an alternative to using the Javascript: document.documentElement.outerHTML that possibly utilizes the jQuery selector and other jQuery methods if they exist. Or, if there is any other more efficient ways of getting a string containing the entire source code 开发者_StackOverflow社区of a webpage using Javascript and or Jquery.


var source = "<html>" + $("html").html() + "</html>";

That was the quick and easy way but, like someone said, it will only return the HTML within the <html></html> tags. It would not include stuff found outside of the <html></html> tags, like the doctype.

To get everything, you can use jQuery.ajax() to request the page and get the whole shebang.

var source = 'Unable to retrieve source code';
$.ajax(
    "your/webpage/here.html",
    {
        async    : false,
        success  : function(data) {source = data;}
    }
);
alert(source);    // or whatever

The request was made synchronously, in this example, so that we could do whatever with the source after the request returns. You could make the call asynchronously and put all of your code in the success function.

Here's the fiddle
http://jsfiddle.net/4rkdF/


Using just jQuery I'd probably do something like this:

$('#theDesiredElement').wrap('<div/>').parent().html();

http://jsfiddle.net/robert/d4WCg/


example markup:

<div id="help"> help </div>

jQuery

var outerHTML = $('<div>').html($('#help')).html();

create <div> on the fly using $('<div>'). Then get <div id="help"> by $('#help'). Afterward put $('#help') inside the created div. And get the html of the created div.

0

精彩评论

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