Outputting dynamic HTML

<p>This is some <b>HTML</b> content placed inside the <i><p> tag</i>.</p>

To print the above HTML code with JavaScript, we could use the document.write () method as:

document.write ("<p>This is some <b>HTML</b> content placed inside the <i><p> tag</i>.</p>");

The following shows the output if you place the above document.write () statement inside a JavaScript script block:

So if you have not noticed already, you can place HTML tags directly inside document.write () method. The following shows a more complex example:

<script language="javascript">
document.write("<p>Creating an unordered list with JavaScript:</p>");
document.write("<ul id='indent20px'>");
document.write("<li>HTML</li>");
document.write("<li>ASP</li>");
document.write("<li>CSS</li>");
document.write("<li>Dreamweaver</li>");
document.write("<li>JavaScript</li>");
document.write("<li>Scripting tools</li>");
document.write("<li>XHTML</li>");
document.write("<li>XML</li>");
document.write("</ul>");
</script>

So in this example, we create an unordered list. Notice each of document.write () method takes only one string argument. The following shows the list

If you wanted, you could combine your strings with the concatenation + operator as shown below to improve the above example:

<script language="javascript">
var dynamicHTML;
dynamicHTML = "<p>Creating an unordered list with JavaScript:</p>";
dynamicHTML += "<ul>";
dynamicHTML += "<li>HTML</li>"
dynamicHTML += "<li>ASP</li>"
dynamicHTML += "<li>CSS</li>"
dynamicHTML += "<li>Dreamweaver</li>"
dynamicHTML += "<li>JavaScript</li>"
dynamicHTML += "<li>Scripting tools</li>"
dynamicHTML += "<li>XHTML</li>"
dynamicHTML += "<li>XML</li>"
dynamicHTML += "</ul>"
document.write(dynamicHTML);
</script>

In this example, we use the concatenation + operator to combine our strings. For instance, line 4, dynamicHTML += "<ul>";, adds "<ul>" to "<p>Creating an unordered list with JavaScript:</p>" (from line 3) to result in

"<p>Creating an unordered list with JavaScript:</p> <ul>"

Also, you can also use both HTML and JavaScript to produce some output, for instance:

<p>Creating an unordered list with JavaScript:</p>
<ul>
<script language="javascript">
var dynamicHTML;
dynamicHTML += "<li>HTML</li>"
dynamicHTML += "<li>ASP</li>"
dynamicHTML += "<li>CSS</li>"
dynamicHTML += "<li>Dreamweaver</li>"
dynamicHTML += "<li>JavaScript</li>"
dynamicHTML += "<li>Scripting tools</li>"
dynamicHTML += "<li>XHTML</li>"
dynamicHTML += "<li>XML</li>"
document.write(dynamicHTML);
</script>
</ul>

In this example, our paragraph is created with HTML. The <ul> tag is opened and closed with HTML as well. However, each item of our list is created with JavaScript. Note our output remains the same despite the fact that we used static (HTML) and dynamic (JavaScript) content.