Le_Coeur
Le_Coeur

Reputation: 1541

Converting html page represented as text to dom object

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

Answers (2)

kubetz
kubetz

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

Esailija
Esailija

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

http://jsfiddle.net/wEyvr/2/

Upvotes: 0

Related Questions