how can i create an image array, each with a unique id using getElementById in javascript? -


here code have when try use image reference value null. want able use access image in table , change src property 1 in preloadimages array. have made table can't reference individual elements of preloadimages array. want each image have unique id using document.getelementbyid('id') please help!! appreciated!

var preloadimages = new array(); size = 52;    for(var h=0; h<size; h++){     preloadimages[h] = new image();       preloadimages[h].src = h+'.png';     preloadimages[h].height =100;     preloadimages[h].width = 70;     preloadimages[h].id = "cardimage"+h+"";                   var cardimageref = document.getelementbyid("cardimage"+h+"");     document.write(cardimageref+'h'); //this line testing, returns null } 

you cannot use getelementbyid() unless element exists in dom tree. modification add them dom:

for(var h=0; h<size; h++){     preloadimages[h] = new image(70, 100);        // size here     preloadimages[h].src = h+ ".png";     preloadimages[h].id = "cardimage" + h;       document.body.appendchild(preloadimages[h]);  // add dom, or parent element      var cardimageref = document.getelementbyid("cardimage" + h);     document.write(cardimageref + "h"); //this line testing, returns null } 

however, since have elements referenced in array element there using index id (instead of using id @ all). tend faster if page layout has several elements.

var image = preloadimages[index]; 

if using images not identifiable index could (but not relevant in case):

function getimage(id) {    for(var = 0; < preloadimages.length; i++) {      if (preloadimages[i].id === id) return preloadimages[i];    }    return null; } 

so use here, example:

for(var h=0; h<size; h++){     preloadimages[h] = new image(70, 100);        // size here     preloadimages[h].src = h + ".png";     preloadimages[h].id = "cardimage" + h;               }  document.write(getimage("cardimage0")); 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -