Multiline document.write

I was just refactoring some HTML and needed to move some of my markup out of the HTML file and into a JavaScript method so I can re-use it in multiple HTML files. Using document.write, I didn’t want to put all of the HTML on one line, and also didn’t want to have to add the concatenation operator to each line. I did a quick search for “javascript document.write multiple lines” in google and came up with a useful little tidbit. If you don’t mind the output of the HTML all on one line you can just escape the newline characters in your method call like this:

document.write('<div id="outer">\
<div id="inner">blah blah blah</div>\

super simple way to keep your code easy to read without too much work. All I did was use a search and replace to find all “\n” characters and replace them with “\\n”.

Thanks to Bernard Marx’s post on webmasterworld for this info!

Post a Comment

Your email is never shared. Required fields are marked *