0

I have some occasions where I need to build a string via JavaScript to append to a HTML element.

My method has generally been to do something like this:

document.getElementById('theID').innerHTML=document.getElementById('theID').innerHTML+'<li>theString</li>';

and that works fine unless the appended string is advanced HTML that includes both JavaScript variables and text. In those cases it becomes a jumbled mess to maintain unless it still has the code spacing (whitespace).

Example of what I would like to have:

document.getElementById('theID').innerHTML=
document.getElementById('theID').innerHTML+
"<ul>
  <li><a href='"+varLink+"'>"+var1+"</a></li>
</ul>";

My problem is that it can't have it have any whitespace or I get an unterminated string literal on page load. Even a space after and before a '+' for concatenation causes the error. If I remove all whitespace from the string then it works fine, but like I said, it's hard to maintain/edit.

First off, is there a better way to do this through jQuery that won't generate that same error on page load? Barring that, is there some way to have the whitespace without getting the unterminated string literal?

Joshua Walcher
  • 506
  • 4
  • 14
  • are you saying that your above code works as is, but breaks if the `innerHTML+'
  • ...'` is changed to `innerHTML + '
  • ...'` ??
  • – nickf Nov 17 '11 at 14:08
  • It's more likely some embedded quotes are throwing it off. – Dave Newton Nov 17 '11 at 14:10
  • @nickf - yes, that is what I'm saying. adding a space either within the concatenated string (i.e. within quotes) or before or after a plus symbol in the contatenated string causes the unterminated string literal. I edited my example to show what I mean. – Joshua Walcher Nov 17 '11 at 14:14
  • @Dave Newton - yeah, I spent several hours the first time I had this happen chasing that down, but it really is the whitespace (or more specifically, spaces) in the code that is causing the unterminated string literal. If I take the same code and remove all spaces, it works fine. – Joshua Walcher Nov 17 '11 at 14:14
  • @DaveNewton - clarification - if I remove all spaces outside the quotes and tags, it works. It's fine to have spaces within any HTML element outputted to the browser, but not if it is outside the tag (i.e. Whitespace) or apparently outside the quotes next to the concatenation symbol. – Joshua Walcher Nov 17 '11 at 14:23
  • Multi-line JS strings need to end with a `\`, you can't just embed a newline like that. – Dave Newton Nov 17 '11 at 15:21
  • @DaveNewton - Thanks, I thought it was spaces, but you're right, it's line breaks. Good to know. – Joshua Walcher Nov 18 '11 at 14:46