Hi,
That's the idea, but id is an attribute of the tag itself:
HTML Code:
<td id="firstCompany">stuff will appear here</td>
To access the element you would use:
document.getElementById('firstCompany');
document.all only works for ie browsers the correct way to access it is with the method demonstrated above. Other things to remember is that every id has to be unique and document.getElementById has to be written exactly like it is above (lower case word, upper first letter, upper first letter and so on).
Here is a demonstration of how you can display array elements dynamically in a td using document.getElementByID:
HTML Code:
<html>
<head>
<title>Editor Results</title>
<style type="text/css">
table {
border-collapse: collapse;
width: 500px;
border: 2px ridge #eee;
font: 8pt verdana, sans-serif;
}
th {
padding: 4px;
background: #fff;
}
td {
border: 1px solid #333;
color: #000;
background: #eee;
padding: 4px;
font-size: 9pt;
}
</style>
<script type="text/javascript">
var company = new Array("American Republic Insurance Co.",
"Briggs Corporation","Grinnell College",
"Iowa Workforce Development","MidAmerican Energy");
var i = 0;
function displayCompanies()
{
if(i == company.length) i = 0;
document.getElementById('display').innerHTML = company[i];
document.getElementById('numbs').innerHTML = "company["+i+"]";
i++;
}
</script>
</head>
<body>
<table>
<tr>
<th>Companies Array</th>
</tr>
<tr>
<td id="display">
Array Values
</td>
</tr>
</table>
<a href="#" onclick="displayCompanies();
return false;">Display( displayCompanies() )</a> |
<span id="numbs">
company[]
</span>
<p>
<pre>
var company = new Array("American Republic Insurance Co.",
"Briggs Corporation","Grinnell College",
"Iowa Workforce Development","MidAmerican Energy");
var i = 0;
function displayCompanies()
{
if(i == company.length) i = 0;
document.getElementById('display').innerHTML = company[i];
document.getElementById('numbs').innerHTML = "company["+i+"]";
i++;
}
</pre>
</p>
</body>
</html>
Just keep clicking on the display link to go through the array elements one at a time.
The relevant code that makes it work is this:
Code:
document.getElementById('display').innerHTML = company[i];
document.getElementById('numbs').innerHTML = "company["+i+"]";
HTML Code:
<td id="display">
...and
<span id="numbs">
2 different id's being set dynamically with new content every time you click display. Let me know if you need more explanation on how it works.
-xDev
Bookmarks