Javascript DOM createElement method provides the functionality to create the span element at runtime of HTML web page. You can insert the new span tag into the HTML body or any previously created static HTML element in the body of HTML document such as <div> tag or paragraph <p> tag. createElement accepts the parameter as HTML element name e.g. span and creates its Javascript object. You can access the various properties and methods of the dynamically created span tag such as style function and its properties, id property, title property. Also you can alter the innerText or innerHTML of the span tag dynamically. Javascript DOM appendChild method enables you to add the newly created element into the HTML body element or nay other HTML element by accessing it using document.getElementById.
Example of Javascript Create Span Dynamically
<html>
<head>
<title>Javascript Create Span Using Document CreateElement Dynamically</title>
<style type="text/css">
.dynamicSpan {
font-size: 11px;
font-family: verdana;
color: Orange;
}
</style>
<script type="text/javascript" language="javascript">
<![CDATA[
function createSpan() {
var spanTag = document.createElement("span");
spanTag.id = "span1";
spanTag.className = "dynamicSpan";
spanTag.innerHTML = "<b>HTML Span tag</b> "
+ "created by using "
+ "Javascript DOM dynamically.";
document.body.appendChild(spanTag);
}
]]>
</script>
</head>
<body>
<center>
<b>Click this button to create Span Tag dynamically:</b>
<input id="btn1"
type="button"
value="create span"
onclick="createSpan();" />
</center>
<br />
</body>
</html>
Above example shows the use createElement method of Javascript DOM that provides the functionality to create the span tag dynamically and append the HTML body tag by passing the spanTag object to the appendChild function to insert the new child element.
Continue to next tutorial: Javascript Getting Div Height Problem in IE to learn how to get div height in internet explorer.