Friday, July 11, 2008

Generating HTML on-the-fly with JavaScript

Example code to generate HTML dynamically using JS. Here we select the HTML element by ID and append our content to its existing content.


<html>
<head>
<title>Append HTML to the div block using JavaScript</title>
</head>

<script>
function appendContent(){
var c1 = document.getElementById('container1'); // get the container element
var p1 = document.createElement("p"); // create a new p tag element
var t1 = document.createTextNode('some generated text!'); // some text to display
p1.appendChild(t1); // put our text into the p tag
c1.appendChild(p1); // append the p tag and its content to the div labeled "container1"
}
</script>

<body>
<div id="container1" style="border: 1px solid blue">
<p>append stuff here!</p>
</div>
<form>
<input type="button" onClick="appendContent();" value="Append to the div block" />
</form>
</body>
</html>

No comments: