How to insert HTML into JavaScript

This article explains how to insert HTML code into a program written in JavaScript, rendering it as HTML.

The method used to do this is called document.write. As this method takes the quotation marks as delimiters of the text to be shown, when a quotation mark belongs to the HTML code we should indicate this by using a backslash right at its left hand side.

As an example, the following code in JavaScript uses HTML to show a text in red color:

<script type="text/javascript">

  document.write("<font color=\"red\">This text will be seen in red</font>");


As shown in this example, we had to put a backslash when we assigned a value to the color attribute of the font tag, which in this case was red. If we had not used those backslashes, the HTML code would have interfered with the proper functioning of the JavaScript method.

This way you can insert any HTML code you want within a JavaScript program, rendering it as HTML.

JavaScript Manual >> How to insert HTML into JavaScript

© Copyright 2010-2017 ROM Cartridge

How old was John Travolta in Pulp Fiction?