Every now and then, you’ll be faced with a situation where you need to dynamically update HTML content. One situation where this may occur is if you have an HTML form whose fields change based on specific selections. Another situation would be updating the content of a dynamic modal window. But where do you store this dynamic content? This article explains three techniques; each one with its own pros and cons.
1. <textarea> method
You can store a block of HTML inside a <textarea> and set it’s display CSS attribute to none:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
$('divContainer').innerHTML = $('txtContent').value;
};
function $(el) {
return document.getElementById(el);
}
</script>
</head>
<body>
<div id="divContainer"></div>
<textarea id="txtContent" style="display: none;">
<h1>
Hello World!
</h1>
</textarea>
</body>
</html>
pros:
- Easy to read and edit content, as there are no special characters required.
cons:
- The content of your <textarea> will be read by search engines as text, and will seriously impact the keywords considered important on your site.
- This method will not work if your dynamic content contains a textarea. You will run into an issue of having nested <textarea> elements, which will break functionality.
2. JavaScript array method
Content can be stored inside a JavaScript array. The array can then be joined into a string:
<html>
<head>
<script type="text/javascript">
var content = [
"<h1>",
"Hello World!",
"</h1>"
];
content = content.join('');
window.onload = function() {
$('divContainer').innerHTML = content;
};
function $(el) {
return document.getElementById(el);
}
</script>
</head>
<body>
<div id="divContainer"></div>
</body>
</html>
pros:
- Clean formatting and fairly easy to work with.
cons:
- Requires each ‘line’ to have quotes around it, with a comma at the end of each line.
- Requires the javascript join() method to be run. While this is a native method and is quite fast, it is still extra processing which needs to be done.
3. Multi-line JavaScript string method
Content can be stored as a multi-line JavaScript string:
<html>
<head>
<script type="text/javascript">
var content = " \
<h1> \
Hello World! \
</h1>";
window.onload = function() {
$('divContainer').innerHTML = content;
};
function $(el) {
return document.getElementById(el);
}
</script>
</head>
<body>
<div id="divContainer"></div>
</body>
</html>
pros:
- Clean formatting and easy to work with.
cons:
- If you are planning on minifying your code, all whitespace from indentations will be preserved. This will impact how well your code can be compressed.
I usually use the third option. It is easy to maintain large blocks of content, and keeps content out of your HTML, thus ensuring that search engines aren’t reading your HTML content as if it were text.




