Handling HTML

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

Clipboard

To do:
Verify which browsers this works on.

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.



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

JavaScript/Handling_HTML
 



 

Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.


Manage research, learning and skills at defaultlogic.com. Create an account using LinkedIn to manage and organize your omni-channel knowledge. defaultlogic.com is like a shopping cart for information -- helping you to save, discuss and share.


  Contact Us