Reputation: 6823
I'm using jquery and have an entire html page stored in var page
var page = '<html>...<div id="start">......</div><!-- start -->....</html>';
How can I extract only the section that starts with <div id="start">
all the way to after the end tag </div><!-- start -->
such that my output is
<div id="start">......</div><!-- start -->
Upvotes: 2
Views: 156
Reputation: 13542
if it's valid html, it would be easiest to just let the browser do it for you. Something like this would do the trick:
var page = '<html><head><title>foo</title><body><div id="stuff"><div id="start">blah<span>fff</span></div></div></body></head></html>';
var start_div = $('#start', page).parent();
alert( start_div.html() )
You can see this example in action at jsFiddle.
[edit] as @Nick pointed out above, this would probably not include the html comment at the end of the div. It also might not work in all browsers -- I don't know -- you should test it. Post back and let us know.
Upvotes: 2
Reputation: 15231
An appropriate regular expression will get you what you are looking for. Try using a line like this:
var start = page.match(/(<div id="start">[\s\S]*?<\!-- start -->)/)[1];
This uses JavaScript's match method to return an array of matches from your page string, and puts the first parenthetized sub-match (in this case, your #start tag and the following comment), into start
.
Here's a demo that shows this method working: http://jsfiddle.net/Ender/mphUj/
Upvotes: 1
Reputation: 53359
var start = page.match(/(<div id="start">.*?<!-- start -->)/m)[1];
Upvotes: 1
Reputation: 7183
regex. or the lazy way (which I don't recommend but is quick..) would be to create a hidden DIV, throw it in the div and do a selector for it
$('#myNewDiv').next('#start').html();
Upvotes: 1
Reputation: 124888
This should do it:
var result = $(page).find('#start')[0].outerHTML;
Upvotes: 1