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?

0

2 Answers 2

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')`?

Sign up to request clarification or add additional context in comments.

Comments

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 */);

2 Comments

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.
@user3538195 See this demo. But if the image is initially hidden, then see this one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.