JavaScript/Handling HTML
Previous: XMLHttpRequest Index Next: Handling JSON

Handling HTML returned from AJAX is surprisingly difficult. Since XMLHttpRequest was designed to work with well-formed XML, attempting to parse an HTML page with the responseXML property almost invariably produces an XML parse error. The responseText property contains the HTML source, of course, and one can attempt to parse this with regular string functions or regular expressions. However, the XMLHttpRequest object does not provide an easy way to parse returned HTML with DOM operations.

Using the browser's HTML parser

One way to parsing HTML returned from AJAX is to add the entire page as a child of the current document in the browser. Simply create a new node and place the returned HTML text in the new node's innerHTML property, as shown below:

var htmlDoc = document.createElement('div');  // Creates a new, empty DIV node.
htmlDoc.innerHTML = ajaxResult.responseText;  // Places the returned HTML page inside the new node.

The HTML document is parsed automatically, and can then be searched, navigated, and manipulated with DOM operations.


Previous: XMLHttpRequest Index Next: Handling JSON

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.


Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us  |  About |  IT Training & References |  IT Careers |  IT Hardware |  IT Software |  IT Books