-Lost wrote:
vu******@gmail.com wrote:
>I have array elements referenced to HTML objects:
myArr[0] = document.getElementById("myDiv1");
myArr[1] = document.getElementById("myDiv2");
How do I reference to these HTML objects through array using object's
properties to make something like:
myArr["some_proprty_here"].innerHTML = "div content changed"
If you are using an Array as a plain object, then it is much better to
use an Object:
var obj = {};
obj[propertyName].innerHTML = '...';
>I know this can be done but I do not see how.
Create a function to store all the IDs that you want into an array
indexed by the IDs you fetched. Something like:
I think it would be more efficient to use an object of references.
var arrayOfIDs = [], ps = document.getElementsByTagName('p');
for (var i = 0; i < ps.length; i++)
{
if (ps[i].id)
{
arrayOfIDs[ps[i].id] = document.getElementById(ps[i].id);
It doesn't seem to be a good idea to sift through all the elements to
find the ones that have an ID, then use it's ID property with
getElementById to return the same object so it can be stored in an array.
If the intention is to store just the id, then:
if (ps[i].id) arrayOfIds.push(ps[i].id);
will do the trick. If the intention is to store an array of element
references, then:
if (ps[i].id) arrayOfEls.push(ps[i]);
If the intention is to have an object with property names that are the
same as the element IDs and have their values reference the matching
elements, then:
var obj = {};
if (ps[i].id) obj[ps[i].id] = ps[i];
I doubt that this method offers any speed advantages, however it might
be preferable for other reasons.
--
Rob