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?
Your problem isn’t spaces, its line breaks in the middle of strings. You can get around that with
\but as Alex K mentioned, that is non standard.For what its worth, I’d do something like this.
Create an array, join the values and append them to innerHTML. You can add your whitespace for presentation without errors.
P.S. This is essentially Alex K’s answer with some tweaks, I upvoted his.