I'd like to know your thoughts about HTML code generation in my JS code.
I just think that the html.push("<tag>" + something + "</tag>")
style pretty annoying.
I've already tried something with templates inside my HTML file (and put some placeholders therein), and then used its content to a replace the placeholders to my real values.
But maybe you guys have other ideas, possibly one using jQuery.
I'd like to know your thoughts about HTML code generation in my JS code.
I just think that the html.push("<tag>" + something + "</tag>")
style pretty annoying.
I've already tried something with templates inside my HTML file (and put some placeholders therein), and then used its content to a replace the placeholders to my real values.
But maybe you guys have other ideas, possibly one using jQuery.
Share Improve this question edited Jun 4, 2009 at 19:49 sth 230k56 gold badges287 silver badges369 bronze badges asked Jun 4, 2009 at 19:47 gsbgsb 1,2291 gold badge16 silver badges31 bronze badges 2- What did you not like about a templating solution? – Nosredna Commented Jun 4, 2009 at 19:51
- could you give more details and/or an example? I'm not sure what you're trying to do. Are you trying to construct HTML to call something.innerHTML = myhtmlstring, or are you trying to use the DOM appendChild / replaceChild functions? – Jason S Commented Jun 4, 2009 at 19:52
6 Answers
Reset to default 5jQuery is the way to go. You can do things like this:
// create some HTML
var mySpan = $("<span/>").append("Something").addClass("highlight");
- it is cross-browser patible,
- it is an easy to use syntax
There is also a templating plugin.
You can use createelement
, appendchild
, and innerHTML
to do this.
Here's an article from A List Apart that uses these functions in the process of generating a dropdown menu.
jQuery has javascript template plugins like jBind and jTemplate. I haven't used them myself but I do remend jQuery whenever possible.
A note on html generation, it is not searchable by search engines in most cases.
I'm a big fan of how PrototypeJS handles templates.
First you create an instance of the Template class and pass it a string containing the template HTML.
var tpl = new Template('Here is a link to <a href="#{link}">#{sitename}</a>');
Then you pass it data containing the values to replace within the template.
$('someDiv').innerHTML = tpl.evaluate( {link: 'http://www.stackoverflow.', sitename: 'StackOverflow'} );
In the above example, I have a div with id="someDiv" and I'm replacing the contents of the div with the result of the template evaluation.
Resig has a little blog entry on creating a very lightweight template system.
There are a bunch of JQuery function that support this. In particular, you should look at append(content)
, appendTo(content)
prepend(content)
prependTo(content)
, replaceWith(content)
, after(content)
, before(content)
, insertAfter(content)
, and insertBefore(content)
.