1

I'm building an iPhone app using Appcelerator Titanium, and I need to convert a HTML string (which may contain invalid HTML like missing tags, not my fault) to a DOM object. In this DOM element I need to find a specific <div>, and put the contents of this <div> in a WebView.

Anyway, I am looking for something like the Simple HTML DOM script, which is for PHP, to search through the DOM for this <div>. I'd like the script to scan the (invalid) HTML string, and get the innerHTML of the <div>.

How can I best do this in JavaScript?

Dexwell
  • 65
  • 8

1 Answers1

2

The code below is the basic string-to-DOM convertor. See the linked answer for a detailed explanation.

function string2dom(html, callback){    
    /* Create an IFrame */
    var iframe = document.createElement("iframe");
    iframe.style.display = "none";
    document.body.appendChild(iframe);

    var doc = iframe.contentDocument || iframe.contentWindow.document;
    doc.open();
    doc.write(html);
    doc.close();

    function destroy(){
        iframe.parentNode.removeChild(iframe);
    }
    if(callback) callback(doc, destroy);
    else return {"doc": doc, "destroy": destroy};
}

This code snippet does not sanitise the HTML. Scripts will be executed, external sources will be loaded. The explanation of the code, and HTML sanitiser can be found at this answer

Usage (examples), Fiddle: http://jsfiddle.net/JFSKe/:

string2dom("<html><head><title>Test</title></head></html>", function(doc, destroy){
    alert(doc.title); /* Alert: "Test" */
    destroy();
});

var test = string2dom("<div id='secret'></div>");
alert(test.doc.getElementById("secret").tagName); /* Alert: "DIV" */
test.destroy();
Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks for your reply. However, Titanium doesn't recognise the `document` property since it doesn't exist. Is it possible to convert the string to DOM in another way? – Dexwell Oct 16 '11 at 20:10
  • 1
    Titanium doesn't provide any DOM methods. If your desired document fragment is well-structured, using a RegExp wouldn't hurt. Otherwise, I recommend to take a look at the Appcelerator Q&A: http://developer.appcelerator.com/questions/tag/dom – Rob W Oct 16 '11 at 20:29