Reputation: 33
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?
Upvotes: 0
Views: 841
Reputation: 2086
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')`?
Upvotes: 2
Reputation: 288680
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 */);
Upvotes: 0