Fluent JS to HTML
11 August 2010A discussion came up at work about concatenating strings in JavaScript to produce html and we thought it would be a good idea to be able to write simple, fluent JavaScript which would generate the structured html easily and in a readable way.
So I wrote a quick prototype that will generate this html in a nice and readable way.
<div id="idtest" class="test"> <p>This is a paragraph<a href="/test.html">Link 1</a></p> <p>Paragraph 2<a href="/test2.html">Link 2</a></p> </div> <div> <ul class="list"> <li>Test</li> <li>Test 2</li> </ul> <p>Test!</p> </div>
You can see the actual code here. So with this code this html can be generated like this;
<script type="text/javascript">
alert(
html()
.div({ className: 'test', id: 'idtest' })
.add(function(){
this.p('This is a paragraph')
.a({href: '/test.html', text: 'Link 1'});
this.p('Paragraph 2')
.a({href: '/test2.html', text: 'Link 2'});
})
.div().ul({className:'list'})
.add(function() {
this.li("Test");
this.li("Test 2");
})
.p("Test!")
);
</script>
How it works
Chained methods append the following element to the previous element. And the add method will add all sub elements as children of the element that add was called on.
So html.div() will return <div></div>, html.div().p(“test”) will give you <div><p>test</p></div> and html.div().add(function() { this.p(); this.p(); }) will give <div><p></p><p></p></div>.
This works by creating a document fragment and building up the html structure in the fragment rather than concatenating strings to produce the html. The toString method then returns the innerHTML.