Hello World! and I would...">

Create document from string in Gecko

I have a string like this <html><body><div id="message">Hello World!</div></body></html>

and I would like to get the content of a #message element without parsing the HTML myself.

I thought maybe I can create a document object from string in Gecko (this is for Firefox add) but I don't see an easy way.

I noticed that there is a createDocument method , but that doesn't accept a string. I would have to cut out some <html>

of the text and then start counting things again.

Does anyone have any idea? Thank.

EDIT: I think this works for me:

doc = document.implementation.createDocument( "http://www.w3.org/1999/xhtml", "html", null );
doc.firstChild.innerHTML = '<html><body><div id="message">Hello World!</div></body></html>';
node = doc.getElementById( "message" ); 
alert( node.innerHTML );

      

+2


source to share


3 answers


Where do you get the string from? If it is XML you can avoid using DOMParser

.

Otherwise, you need to create an HTML document - https://developer.mozilla.org/en/Parsing_HTML_From_Chrome .



The fact that the use only createDocument

works seems suspicious because people have been using more complex solutions all this time.

+2


source


Don't like answering my own question, but it looks like it worked for me:



doc = document.implementation.createDocument( "http://www.w3.org/1999/xhtml", "html", null );
doc.firstChild.innerHTML = '<html><body><div id="message">Hello World!</div></body></html>';
node = doc.getElementById( "message" ); 
alert( node.innerHTML );

      

+3


source


Is it always syntax? If so, why not use a regular expression?

0


source







All Articles