Given the information just supplied in the comments describing the actual problem you're trying to solve, you don't need to retrieve the body
tag's attributes at all, and nor should you be using string searching. Just do:
var $newContent = $('<div>' + data + '</div>').children();
$(document.body).empty().append($newContent);
i.e. parse the entire data - $(data)
- then get all child nodes, and put those in your existing document.body
.
The <div> + data + </div>
is necessary because $(html)
requires a single element (and children) and won't accept the standard HTML boilerplate of <!DOCTYPE ...><html>...</html>
. It also appears to strip out the <head>
and <body>
tags, leaving behind only their children. In tests I've just made, given
var data = '<!doctype html><html><head></head><body><span>Test</span>' +
'<span>Test 2</span></body></html>'
then
$('<div>' + data + '</div>').children()
gives just the two <span>
elements, i.e. the desired contents of data's <body>
tag.
EDIT OK - it seems that doesn't quite work out as desired because of the stripping of the <head>
and <body>
tags, leaving the original contents of the <head>
in place.
Try this, instead - it's a combination of your original technique, and this one:
var $newContent = $(data.substring(data.indexOf('<body')));
$(document.body).empty().append($newContent);