Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Create DOM node with arbitrary HTML

 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65118
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gamini Sirisena:
innerHTML is not a solution here as it won't create a DOM node.

Huh?
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65118
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not the case.
 
andrew ennamorato
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like you want appendChild()
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic