06/15/2011

Update HTML Content Using Javascript

by Cyle
Categories: javascript
Tags: , , ,
Comments: Leave a Comment

Using JavaScript we are able to change or update the content of an HTML page depending on what the user does. We can change the text and HTML of an element. This can be used in many different ways, and is why this is one of my favorite uses of JavaScript. Let’s start with the basics.

The Basics

We will be using the innerHTML property. Each HTML element has an innerHTML that defines the HTML code and text between the element’s tags. You must give the element you wish to update or change an id. Once it has an id we can use the getElementById function to change only the elements we want with certain ids. Here is a basic example:

1
2
3
4
5
6
7
8
<script type="text/javascript">
function updatetext(){
	document.getElementById('colortext').innerHTML = 'red';
}
</script>
 
The apple is <span id='colortext'>green</span>.
<input type='button' onclick='updatetext()' value='Change Text'/>

The above results in:

The apple is green.

Updating User Defined Text

Now let’s take this one step further. We can add a text area where the user can decide what the text should be. Using the example above, we will add a text box so the user can decide what to change the text to.

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript">
function updatetext(){
	var userInput = document.getElementById('userInput').value;
	document.getElementById('colortext').innerHTML = userInput;
}
</script>
 
The apple is <span id='colortext'>green</span>.
<input type='text' id='userInput' value='Apple Color' />
<input type='button' onclick='updatetext()' value='Change Text'/>

The above results in:

The apple is green.


Changing HTML

Not only can we change the text, but can also change the HTML of an element the exact same way. We can expand on the last example and add some color to our element using HTML tags.

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript">
function updatetext(){
	var userInput = document.getElementById('userInput').value;
	document.getElementById('colortext').innerHTML = "<span style='color:" + userInput + "'>" + userInput + "</span>";
}
</script>
 
The apple is <span id='colortext'>green</span>.
<input type='text' id='userInput' value='Apple Color' />
<input type='button' onclick='updatetext()' value='Change Text & Color'/>

The above results in:

The apple is green.


Notice how the color changes also (if it is recognized as a color).


Leave a Reply

Your email address will not be published. Required fields are marked *



user-avatar
Today is Tuesday
08/22/2017