Javascript Code to Change Span innerText
Javascript document object can change the innerText property of the HTML elements like span, div, and paragraph etc using getElementById method. You can change the old innerText of the HTML span element or you can use the Javascript string concat function to concatenate the old text and new text into the span <span> tag. String concat function of javascript allows you to insert the new innerText in the beginning or at the ending of the previous text placed inside the <span> tag.
JavaScript DOM Examples:
You can see the live samples and examples of JavaScript DOM from the following links:
The innerText property of HTML elements such as <span>, <div> or <p> paragraph tag does not allow passing the HTML tags in the string value. Instead you can use "\n" backslash n in the string value as a newline character.
Here you have to specify the value of id attribute of <span> tag to access it using the getElementById method of document object. Value of id attribute must be unique in the current HTML document coz getElementById method returns reference to the first occurrence of HTML element with specified id.
Syntax to Change Span innerText
document.getElementById("id").innerText = "value";
innerText property of getElementById method gets or sets the value of innerText property value of the target HTML element.
Javascript Code to change Span innerText
<html>
<head>
<title>Javascript Change Span InnerText</title>
<script language="javascript" type="text/javascript">
<![CDATA[
function changeSpanText() {
var previousInnerText = new String();
previousInnerText =
document.getElementById('span1').innerText;
previousInnerText =
previousInnerText.concat("\n<b>New Text "
+ "added to the span HTML tag.</b>\n");
document.getElementById('span1').innerText = previousInnerText;
}
]]>
</script>
</head>
<body>
<span id="span1">innerText placed inside the span element of HTML.<br />
Javascript will change the innerText of this HTML span element. </span>
<br />
<center>
<input type="button"
value="Change Span innerText"
onclick="changeSpanText()" />
</center>
</body>
</html>
Similarly you can pass the id of any other HTML element such as <div> or <p> tag to change their innerText dynamically using Javascript function.
Output:
You can see the output of above discussed codes from the following link:
Continue to next tutorial: Javascript Code to Change Div Object innerHTML to learn how to change the HTML content inside the div element.
