*
The moose likes HTML, CSS and JavaScript and the fly likes Create DOM node with arbitrary HTML Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Create DOM node with arbitrary HTML" Watch "Create DOM node with arbitrary HTML" New topic
Author

Create DOM node with arbitrary HTML

Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 347
Is there a commonly used way to create a DOM node from a given HTML string in a Javascript?

I've checked google (found some functions written by people, an http service to generate the code necessary for a given piece of html [google html2dom]), javaranch archives and didn't come up with anything useful.

innerHTML is not a solution here as it won't create a DOM node.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60782
    
  65

Originally posted by Gamini Sirisena:
innerHTML is not a solution here as it won't create a DOM node.

Huh?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 347
Unless I am wrong I meant innerHTML does not create DOM node"s". It seems to create one textnode perhaps for the whole string that is added. From what I read in the web this seems to be the case.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60782
    
  65

Not the case.
andrew ennamorato
Ranch Hand

Joined: Oct 03, 2007
Posts: 100
Sounds like you want appendChild()
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 347
Thanks all.
Looks like I was wrong.
The code given below demonstrates this. (You need to change the event name onclock to onclick)


However reading further on innerHTML I still have reservations
on using it. The links here
and here give and idea about
the problems (and advantages) of using innerHTML.

To make things work across browsers I might be tempted to use
innerDOM by Simon K�hn, which is
also suggested by the Mozilla Developers Center here.

Firefox has an implementation of the Range object of the
w3C's DOM Traversal and Range specification
here and implements a Firefox specific method createContextualFragment
here which takes an HTML string and returns a DOM Node.

I guess if something similar were to be adopted by w3C DOM API this would be the standards compliant way for innerHTML like functionality.

For simple display of HTML, innerHTML may be the choice until something
better standards compliant way is available.


[ October 13, 2008: Message edited by: Gamini Sirisena ]
 
Consider Paul's rocket mass heater.
 
subject: Create DOM node with arbitrary HTML
 
Similar Threads
XML document create with Java
DOM & SAX
prevent confirmation after self.close()
find position of a given node
default namespaces are being dropped when sent through a web service