Cofey
Cofey

Reputation: 11404

Where to store a small amount of HTML only used with JavaScript?

I have a small template of HTML that I am using that contains a few DIVs, and a few headers (roughly 15 lines of code). This template is populated with text taken from options that a user selects from another part of the page. The markup is only of any use if the user has JavaScript enabled. It is also cloned if the user selects multiple choices.

What would be the best way to store this template (according to best-practices)?

  1. It seems like storing it in the JS would make sense, since it's only used with JS, but then I know it's best to separate behavior and markup.
  2. Insert the markup in the main page and just set it to display none in the stylesheet, then display block in the JavaScript.

Upvotes: 2

Views: 153

Answers (3)

Victor
Victor

Reputation: 4721

for maintainability I would say #2 is best. If you keep markup in a external JS file or even in the script section it may be ignored or forgotten when the markup is updated. If you are using a CMS tool then it would make more sense to keep it in the markup. I usually shy away from keeping html markup in javascript as it would be easy to make mistakes with escaping characters, and generating compliant markup.

Upvotes: 5

Pierre
Pierre

Reputation: 1343

In this specific case, because of the clone, from my opinion, there is no satisfying solution.

I would use the second, because in the first you "store HTML" in JS... but I suppose this "storage" is done with a string containing HTML. So the string will be evaluated (with jQuery or innerHTML attribute). This is not really clean and efficient.

Moreover, with the second solution, you can edit your HTML with a WYSIWIG editor for instance.

Upvotes: 2

borayeris
borayeris

Reputation: 2650

1st choice is better because it will be cleaner.

Upvotes: 0

Related Questions