0
for (i=0;i<tar.length;i++) {
document.write("<img src=" + tar[i] + " width='100' height='100'>"+"  ");
}  

tar array has image sources, i want to display that using getElementById not by document.write

1 Answers1

0

Using document.createElement and appendChild, you might do:

var myContainer = document.getElementById("someContainerId");

for (i=0;i<tar.length;i++) {
    var myimg = document.createElement("img");
    myimg.src= tar[i];
    myimg.width="100";
    myimg.height="100";

    myContainer.appendChild(myimg);
}

Make sure, of course, that there really is a container element with the id of someContainerId, or whatever id you want to give it. It might be best if the container element were a <div>.

apsillers
  • 101,930
  • 15
  • 206
  • 224
  • i got an error like "Uncaught TypeError: Cannot call method 'appendChild' of null" – user1553487 Feb 11 '13 at 20:36
  • @user1553487 The error is either because you don't have `
    ` in your HTML, or because you're not [waiting to the DOM to load](http://stackoverflow.com/questions/11163060/cannot-set-property-innerhtml-of-null/11163147#11163147).
    – apsillers Feb 11 '13 at 20:43
  • The DOM is the object model of the HTML of your page. **JavaScript code can run before the DOM is ready for use**, so `getElementById` will not work unless it runs after the DOM is loaded. As suggested in the [answer I linked previously](http://stackoverflow.com/questions/11163060/cannot-set-property-innerhtml-of-null/11163147#11163147), either put your code in a `window.onload` handler, or place your ` – apsillers Feb 11 '13 at 20:53
  • i did all the options as you told but its still ends in an error. Plss clear me. – user1553487 Feb 11 '13 at 21:04
  • In general on Stack Overflow, you should be *showing* code rather than *asking* for code. Edit your question to include your current code and people can try to diagnose what is wrong with it. – apsillers Feb 11 '13 at 21:19
  • I ve lot of functions in my program , i want to refresh and call a particular function when a button is clicked. pls answer me – user1553487 Feb 13 '13 at 18:44