Search code examples
javascripthtmlclonemarkup

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.

Solution

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