function sort() {
c.sort()
document.getElementById('display').innerHTML="";
document.getElementById('display').innerHTML=c +'<br>';
}
// document.getElementById('display').innerHTML=c +'<br>';
// can't get <br> tag to print each element on each line.
// c is a array
how can i get each element printed on a new line?
ta
When you call c, you print the whole array at once.
You need to walk through the elements with loop one by one.
Here sample code:
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-
<html>
-
<head>
-
<script type="text/javascript">
-
c = new Array( "Apple", "Lemon", "Banana", "Melon");
-
function sort() {
-
c.sort()
-
container = document.getElementById('display');
-
container.innerHTML = "";
-
for( var i=0; i < c.length; i++ ){
-
//c.length = number of array elements in this case 4
-
//the array looks like this:
-
// c[0] = "Apple"; c[1] = "Lemon"; c[2] = "Banana"; c[3] = "Melon"
-
// So we loop from 0 to 3( i < 4 )
-
container.innerHTML = container.innerHTML + c[i] +'<br>';
-
}
-
}
-
window.onload = sort;
-
// use this to call sort after DOM is loaded, otherwise container will have no properties, because document.getElementById('display') can't get the object, because it doesn't exist yet
-
</script>
-
</head>
-
<body>
-
<span id="display">Some text </span>
-
</body>
-
</html>
-
Hope this helps.
( Sorry for my English. It is not my native language. )