suppose in a variable html is saved like
var vhtm="<div><div id='test'>zebra</div><div id='foo'>here is my many other html content</div></div>";
i want to parse the above html stored in variable with the help of jquery. i need to extract a particular div by id and including its content. the return result would like
<div id='foo'>here is my many other html content</div>
so i need to find div by id like id='foo'
please help me how to parse the above like jquery.
5 Answers 5
try something like this :
$(vhtml).find('#foo');
Comments
Try this
var divHtml = $(vhtm).find("#foo").html();
Comments
Since you want the output to contain the whole div including content I'd suggest you use some regular expressions :) Like this maybe:
var vhtm="<div><div id='test'>zebra</div><div id='foo'>here is my many other html content</div></div>";
var regex = /<div id='foo'>.*?<\/div>/;
alert(vhtm.match(regex));
Result:
enter image description here
3 Comments
<div>
inside that div? Its not 'truckload of complex code', but it'll still break it.I don't know of any nice way to do that. I would set this as the HTML contents of an DOM element ($(document.createElement('div')).html(vhtm).find('#foo')
) or create an about:blank
iframe, add the HTML to it and use $(iframe.contentWindow.document.body).find(...)
if it requires isolation from the page you're running the script on for some reason
5 Comments
$(document.createElement('div'))
is equal to $('<div />')
.$.c=function(tagName, attrs, text) { return $(document.createElement(tagName)).attr(attrs||{}).text(text||''); }
(without the useless calls to attrs()
and text()
when there are no arguments, but does the same thing) to make it more readable. I find that even more readable than plain HTML.This should do it:
http://jsfiddle.net/HenryGarle/Vpa3q/
var vhtml="<div><div id='test'>zebra</div><div id='foo'>here is my many other html content</div></div>";
var foo = $(vhtml).find('#foo').html();
alert(foo);