I have a collection of strings which I want to select from to insert text into a page.
The strings are stored in an object/array, like so:
var strings = {
x01: 'Hello world',
x02: 'Goodbye world'
x03: 'The quick brown fox',
x04: 'jumped over'
x05: 'the lazy dog',
x06: 'the fat lady sung'
};
In my HTML, I have span tags that have IDs that correspond to the variables above.
However, on any one page, only some of the spans will show up at any one time. So, for example, there might be only three of them:
<span id="x01"></span>
<span id="x04"></span>
<span id="x06"></span>
What I want to do is be able to search the page to gather up all the IDs that match the naming convention (x followed by two digits), and then match them to the corresponding variable so that I can fill the span with the appropriate text.
Something like (this is a rough outline, not meant to be taken as actual code):
array = getElementsByID(someKindOfMultipleSelect);
for (var key in array)
{
document.getElementById(**IDandVarName**).innerHTML = strings.**IDandVarName**;
}
Despite doing some Googling on this, I’m stuck on two points. I don’t know how to gather the span IDs I want from the page, and I don’t quite know how to match them up once I’ve got them.
Yes, I’m kind of a noob at Javascript, so please be gentle with me in explaining this.
Thank you for any advice.
Below is a pure (and very simple) JavaScript solution. This solution avoids gathering up all the spans on the page (not efficient), and grabs the elements by ID only.
HTML:
JavaScript:
Here’s a working fiddle.