3

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.

2
  • What did you not like about a templating solution? 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? Commented Jun 4, 2009 at 19:52

6 Answers 6

5

jQuery 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 compatible,
  • it is an easy to use syntax

There is also a templating plugin.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

jQuery has javascript template plugins like jBind and jTemplate. I haven't used them myself but I do recommend jQuery whenever possible.

A note on html generation, it is not searchable by search engines in most cases.

Comments

3

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.com', 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.

Comments

3

Resig has a little blog entry on creating a very lightweight template system.

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.