Monday, 29 October 2007

How to change a text using javascript

Are you a JavaScript newbie? Do you need to change the code contained within an HTML element?

The solution is very simple. We have to use the javascript method:

getElementbyId()


...that get an element property (for example, value, style, ecc...) by the element ID (for example <div id="myLayer">) and:

.innerHTML="a piece of html code";


... that rewrite the layer content with the HTML code specified. A typical syntax is:

document.getElementById('myLayer').innerHTML ='<strong>Hello World!</strong>';


This code (you have to add it inside a javascript function to work!), change the content of an html element with ID "myLayer" (for example a DIV, H1, H2, SPAN, A...), with <strong>Hello World!>


Download this tutorial



Example 1: A simple text change javascript function

<script language="javascript">
function changeTextSimple(idElement){
document.getElementById.('element'+idElement).innerHTML ='<strong>Hello World</strong>';
}</script>


Example 2: change the text of a <li> element inside an <ul> element
changeText() is a simple function that change the content of a <li> element:

<script language="javascript">
function changeText(idElement){
if(idElement==1){
document.getElementById('element'+idElement).innerHTML ='<a href="http://www.google.com">Google</a>';
} else if(idElement==2){
document.getElementById('element'+idElement).innerHTML ='<a href="http://woork.blogspot.com">Woork</a>';
}
}
</script>

<ul>
<li id="element1">Google</li>
<li id="element2">Woork</li>
</ul>
<a href="#" onClick="javascript:changeText(1)">Change Google into a link</a><br/>
<a href="#" onClick="javascript:changeText(2)">Change Woork into a link</a><br/>


Frequent Errors
When you pass a variable to a Javascript function from an HTML page remember this:

If the parameter is a number the syntax is:
<a href="#" onClick="javascript:changeText(1)">change</a>


else if the parameter is a string the syntax is:
<a href="#" onClick="javascript:changeText('element1')">change</a>

With quote (') around the element name.

No comments:

Post a Comment