I may want to display different versions of charts of the SAME stock symbol so it needs using "var". (Other uses I have are weather charts or traffic cams etc, so I have broader applications). I'll illustrate it with stock charts.
By trial and error I found using the id="x" and "document.getElementById" works, but it needs careful bookkeeping of the SAME and unique id TWICE on each line. (Breaking the line instead of a "long line" makes it even harder to keep id's straight)
Imagine with dozens of additional lines of chart variations it becomes tedious.
Is there a better way? How would you code it to produce a "collage of graphs"?
<script> var sym = "MSFT" </script>
<h1><strong> <body> Symbol <script> document.write(sym); </script></body><br>
<img src="" id="i1">$ <script> var a = document.getElementById('i1'); a.src = "http://www.google.com/finance/chart?cht=o&tlf=12h&q=" + sym ; </script>
<img src="" id="i2">% <script> var a = document.getElementById('i2'); a.src = "http://www.google.com/finance/chart?cht=c&tlf=12h&q=" + sym ; </script>
<!-- etc. perhaps dozens more different charts for the same symbol -->
I would remove all of the <script>
tags from inside the HTML. This keeps document structure and behavioral logic separate. Here's an example using a loop and string concatenation that should be expandible:
<h1 id="title"></h1>
<img src="" class="symbol" alt="stock chart">$
<img src="" class="symbol" alt="stock chart">%
<!-- etc. perhaps dozens more different charts for the same symbol -->
<script>
const sym = "MSFT";
const urls = [
"http://www.google.com/finance/chart?cht=o&tlf=12h&q=",
"http://www.google.com/finance/chart?cht=c&tlf=12h&q="
];
document.getElementById("title").innerHTML = "Symbol " + sym;
const symElems = document.getElementsByClassName("symbol");
for (let i = 0; i < symElems.length; i++) {
symElems[i].src = urls[i] + sym;
}
</script>
You might want to use an object instead of an array for the URLs, and add ids to your <img>
tags depending on your needs. The problem with not using a class name is that it might be easier to lose track of how many elements are in the collection you're manipulating (not to mention styling). You may also wish to dynamically generate the <img>
elements using document.createElement("img")
and set the properties in JS:
<h1 id="title"></h1>
<div id="sym-container"></div>
<script>
const sym = "MSFT";
const urls = [
"http://www.google.com/finance/chart?cht=o&tlf=12h&q=",
"http://www.google.com/finance/chart?cht=c&tlf=12h&q=",
"http://www.google.com/finance/chart?cht=g&tlf=12h&q=",
"http://www.google.com/finance/chart?cht=s&tlf=12h&q="
];
document.getElementById("title").innerHTML = "Symbol " + sym;
const symContainer = document.getElementById("sym-container");
urls.forEach(e => {
const symElem = document.createElement("img");
symElem.src = e + sym;
symContainer.appendChild(symElem);
});
</script>