How to extract all contents inside a div from HTML string in JavaScript

I have a HTML string like this :-

var html = '<div id="parent_div">
            <div id="child_div">
            <ul>
             <li><img src="wow/img1.jpg" /><a href="http://wow.com">wow link</a></li>
             <li><img src="wow/img2.jpg" /><a href="http://wow.com">wow link</a></li>
            </ul>
            </div>
            </div>';

How to extract all the contents inside the <div id="parent_div"> ?


Solution 1:

In jQuery you could just do $($html).html();

In php you could use something like Simple HTML DOM

Solution 2:

String is a string. Use a regex to parse it.

On JS side:
Take a look at replace or match
Something like (not tested):

pattern = '/<div id="parent_div">(.*?)<\/div>/';
matches = html.match(pattern);
result= matches[1];

This probably doesn't work because it will stop on the first </div>, but regex is the way to go here, just find an expression which returns what you need.

Generally I think it is a bad idea to "hardcode" HTML in PHP or JS variables.
IMHO it is better to use a template engine, which can be used on both sides (client and server) like Mustache. It providers complete separation of HTML from any kind of application logic, client(JS) or server(PHP).