0

I have a series of Arrays and as an output i want to display an image. I know how to do it using document.write but i cant get my head around how i would do something like this using the dom.

document.write("<p><img src='"+stones.value+"' alt='Mick'></p>");

How could i achieve something like this without using document.write?

effernus
  • 33
  • 1
  • 6

2 Answers2

2
 var img = new Image();
 img.src = stones.value;
 img.alt = 'Mick';

 document.getElementById('targetElement').appendChild(img);

I'm using the Image constructor here.

Oriol shows how to do it with pure DOM.

Nice read: Is there a difference between `new Image()` and `document.createElement('img')`?

Community
  • 1
  • 1
phylax
  • 2,034
  • 14
  • 13
0

Using DOM methods:

var p = document.createElement('p'),
    img = document.createElement('img');
img.src = stones.value;
img.alt = 'Mick';
p.appendChild(img);
wrapper.appendChild(p);

Using innerHTML:

wrapper.innerHTML += "<p><img src='"+stones.value+"' alt='Mick'></p>";

Where wrapper is a reference to the element where you want to insert that code. Some examples:

var wrapper = document.getElementById(/* CSS id */);
var wrapper = document.getElementsByClassName(/* CSS class */)[0];
var wrapper = document.querySelector(/* CSS selector */);
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • I hope i am not asking for too much but i cant seem to get this working. A fiddle with an example of an image being hidden and then displayed once a button is clicked would really help if its not too much trouble. Im having a hard time understanding this. – effernus Apr 24 '14 at 19:39
  • @user3538195 See this [**demo**](http://jsfiddle.net/2URjn/). But if the image is initially hidden, then see [this one](http://jsfiddle.net/2URjn/1/) – Oriol Apr 24 '14 at 20:49