Quick question why is it that when I try to do something like this
- Code: Select all
<p><script>document.write(color)</script></p>
<script>
var color = "blue";
</script>
I get a color is not defined error even though color clearly is defined ?
The reason I ask is because I got taught to put scripts at the end of the page to prevent them from blocking the loading of the page, but clearly in a case like this where I want to output the value of a variable to some element on the page that isn’t possible if I have to put the script that holds the variable before the html element in to which I’m inserting the value.
Now while in a simple example like this I could just do something like this
- Code: Select all
<script>
var color = "blue";
document.querySelector('p').innerHTML = color;
</script>
What about if I wanted to do something a little more complicated like inserting a variable into a table for example.
ideally what I'd like to be able to do is something like this
- Code: Select all
<script>
var x_coordinate = 100;
var y_coordinate = 200;
var z_coordinate = 150;
</script>
<table id="coordinates">
<tr>
<td>X</td>
<td>:</td>
<td>javascript:(x_coordinate); km</td>
</tr>
<tr>
<td>Y</td>
<td>:</td>
<td>javascript:(y_coordinate); km</td>
</tr>
<tr>
<td>Z</td>
<td>:</td>
<td>javascript:(z_coordinate); km</td>
</tr>
</table>
as that's a simpler way to go about things or it would be if it actuality worked, now with a small table like the one above I could populate the cells like this
- Code: Select all
var table = document.querySelector('table#coordinates');
table.rows[0].cells[2].innerHTML = x_coordinate;
table.rows[1].cells[2].innerHTML = y_coordinate;
table.rows[2].cells[2].innerHTML = z_coordinate;
But imagine you had a table with hundreds of cells that needed to be populated doing the above becomes completely impractical, so how then could I insert the variables into the appropriate table cells and have there values printed out when I load the page because doing
- Code: Select all
javascript:(variable name);
simply doesn't work, is
- Code: Select all
<script>document.write(variable name)</script>
the only way or is there a more succinct method.