views:

110

answers:

5

Hi,

Does anybody know if there is a tool around that can convert html to javascript.

For example:

<div>
</div>

would convert to

aDiv = document.createElement('div');
document.appendChild(aDiv);

etc

I'm am doing a few html templates for UI components and am using MooShell for prototyping. It would be great to be able to auto-generate the javascript that will build the component's html.

Thanks

A: 

If there was no such tool (which I highly think is the case), I would solve this problem the same old good way: build my own parser.

Khoi
A: 

I'm not sure about your situation, but if you have components in HTML they should have events, IDs and binding... So I don't think there is a human-like genius script that can generate this code. Add to that, your problem is very specific. It may be somewhere in some IT corporation, but it's not something that web developers uses daily like jQuery.

Omar Abid
A: 

I see other people have given you plenty of tips on how to do this, but my two cents on one thing to bear in mind.

If you are inserting/removing/modifying elements to/from the DOM using client-side Javascript, you will notice that with a framework such as jQuery, you will be unable to call and manipulate the DOM elements you have added in on the fly.

The best way round this is to look up using the jQuery Live plugin.

George
A: 

The PrototypeJS Framework has an insert() method which is able to parse html code, so you can do something like:

$$('body')[0].insert(stringWithYourHTMLCode);

Or you define a container for your content:

$('containerId').insert(stringWithYourHTMLCode);
Christian
That's not what he is asking.
Chris
+2  A: 

I'd suggest taking a look at John Resig's pure javascript HTML parser. It consists of a SAX style parser for HTML and includes an XML serializer, a DOM builder and a DOM creator. Each takes a string of HTML as input.

In particular, the HTMLtoDOM method could easily be repurposed to return the string of javascript required to build the DOM for any input string of HTML.

donalmacanri