For example, assuming there is a HTML string
<div id="test_div"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div>
Now it can be parsed using below code.
var html = '<div id="test_div"><ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul></div>'; var parser = new DOMParser(); var wrapper = parser.parseFromString(html, "text/html"); wrapper.getElementsByTagName('li');
The output looks as expected, there are three objects returned.
One thing to keep in mind is that the DOMParser is still an experimental feature and is not standardized yet though many main stream browsers have supported it. And this feature is not supported in old browsers.
Another way of converting HTML to DOM is to use the traditional document.createElement method. After creating the element, the HTML string can be assigned to the innerHTML attribute of the element and the JS engine would parse it to the child elements of the created element.
For the same HTML string above, the code using document.createElement would be
var html = '<div id="test_div"><ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul></div>'; var wrapper= document.createElement('div'); wrapper.innerHTML= html; wrapper.getElementsByTagName('li');
The output would also be expected.
Normally one should use DOMParser if he can but if the application needs to support old version of browsers, these two methods should be combined and a wrapper method should be created on top of them.