0

I have an html component that makes a variable amount of rows in a table. Inside this component there are several css classes e.g

<div class="row" style="margin-left:0">

How do I embed this big chunk of html in a javascript forloop? The only way I know how is to use document.write("") but the quotation marks in the classes will mess that up.

UPDATE: Any ideas why the tags and everything inside them is ignored when using innerHTML??

James
  • 2,951
  • 8
  • 41
  • 55

3 Answers3

2

Make a div with an id of someDiv (or whatever you want) for this to work.

document.getElementById("someDiv").innerHTML = '<div class="row" style="margin-left:0">';

I used single quotes to wrap the string in order to avoid conflict with the double quotes in the HTML.

Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
0

You'll need to escape your quotes in your javascript.

alert('Oh, heya, I didn\'t see you, so "Hello"');
David Yell
  • 11,756
  • 13
  • 61
  • 100
0

JavaScript isn't great for expressing HTML as, amongst other things, it lacks Heredoc syntax which results in you having to escape any string literals (as suggested by @DavidYell).

It might be worth considering the use of a templating engine such as Mustache.js or Underscore.js

Community
  • 1
  • 1
JonnyReeves
  • 6,119
  • 2
  • 26
  • 28
  • What!? Javascript isn't great for expressing HTML? Dude, Mustache and Underscore were *written* in Javascript. – Elliot Bonneville May 09 '12 at 12:43
  • ... and were designed because expressing HTML in Strings is a whole world of pain. It's not like JavaScript even offers [E4X syntax](https://developer.mozilla.org/En/E4X/Processing_XML_with_E4X) by default for working with XML. – JonnyReeves May 09 '12 at 12:47
  • All I can say is Javascript was designed explicitly for the purpose of working with (and that includes expressing) HTML. Underscore doesn't make that any easier. – Elliot Bonneville May 09 '12 at 12:52
  • Hi Elliot, I'm not trying to be difficult here, but expressing any form of XML in JavaScript is painful as you end up having to join a bunch of String literals together. Templating engines provide a clean seperation between the template (HTML) and the data (JavaScript Objects) - if you haven't looked into one yet then may I suggest you have a look at this blog post: http://www.jonnyreeves.co.uk/2012/using-external-templates-with-mustache-js-and-jquery/ – JonnyReeves May 09 '12 at 12:59
  • Nice post. However, it's not *particularly* relevant in this case, as the OP has a very simple issue and installing a templating engine would be a bit like using a backhoe to till a garden. However, templating engines are quite nice when you're working on a really big project in which you're doing lots and lots of this sort of thing. – Elliot Bonneville May 09 '12 at 13:05