Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select body element from string

Tags:

jquery

I have a string <html><head></head><body>test</body></html> and I'm trying to get just the contents of the body using jQuery.

Ive tried

$('<html><head></head><body>test</body></html>').find('body').html();

but that doesn't work.

Any ideas on how to do it?

Edit:

In case it wasn't clear, I need to get the body element from a string, not the DOM.

Edit 2:

Be aware that the method used needs to not return anything form the head element. Such as inline styles.

like image 335
Petah Avatar asked Apr 06 '11 23:04

Petah


4 Answers

var x = '<html><head></head><body>test</body></html>';
x = x.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
alert(x);

Check working example at http://jsfiddle.net/6hPHn/1/

like image 165
Hussein Avatar answered Oct 27 '22 11:10

Hussein


I agree with @RustyTheBoyRobot's answer, using RegEx would work best. It would be far faster than using jQuery to create all of those DOM elements anyway. Try something like this:

var html_page_string = '<html><head></head><body>test</body></html>';
var matches = html_page_string.match(/<body>(.*)<\/body>/ig);

The text you want should be in matches[1]

EDIT

For some reason, removing the g flag seemed to make it group correctly so that the string was in matches[1]:

var matches = html_page_string.match(/<body>(.*?)<\/body>/i);
like image 35
Groovetrain Avatar answered Oct 27 '22 09:10

Groovetrain


It doesn't seem to like that sort of HTML being passed into the jQuery functions, possibly because html is the parent element of a HTML document.

It even doesn't work using native DOM API...

var a = document.createElement('div');
a.innerHTML = '<html><head></head><body>test</body></html>';
console.log(a.innerHTML); // test

jsFiddle of difference between your string and others.

You could use a regular expression...

var str = '<html><head></head><body class="here is some classes">test\ntesty</body></html>';
str = str.replace(/^.*?<body.*?>([\s\S]*?)<\/body>.*?$/, '$1');
console.log(str); // test

jsFiddle.

like image 35
alex Avatar answered Oct 27 '22 11:10

alex


Assuming that your HTML string is valid strict XML and you are using jQuery 1.5, you can use the $.parseXML function.

$($.parseXML('<html><head></head><body><div>test</div></body></html>'))
.find("body").contents()
like image 45
user120242 Avatar answered Oct 27 '22 11:10

user120242