Reputation: 1541
I have a text that represents some page. I need to convert this text to dom object, extract body
element and append it to my dom.
I have used following code to convert text and extract body
element:
$('body', $(text)).length
and:
$(text).filter('body').length
In both cases it returns 0
...
To test: http://jsfiddle.net/wEyvr/1/
Upvotes: 2
Views: 331
Reputation: 8556
jQuery is parsing whole HTML in a non-standard way, so $(html)
doesn't work as expected.
You can extract the content of the body tag using regexp and work from there:
// get the content of the body tags
var body = $(text.match(/<body[\s\S]*?>([\s\S]*?)<\/body>/i)[1]);
// append the content to our DOM
body.appendTo('body');
// bonus - to be able to fully use find -> we need to add single parent
var findBody = $("<body />").html(body.clone());
// now we are able to use selectors and have fun
findBody.find("div.cls").appendTo('body');
HERE is the working code.
EDIT: Changed the code to show both direct append and also using selectors.
Upvotes: 2
Reputation: 140230
Something like this:
var ifr = $("<iframe>"),
doc = ifr.appendTo("body")[0].contentWindow.document,
bodyLength;
doc.open();
doc.write(text);
doc.close();
bodyLength = ifr.contents().find("body").length;
ifr.remove();
alert(bodyLength);
Upvotes: 0