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.
var x = '<html><head></head><body>test</body></html>';
x = x.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
alert(x);
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);
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With