Display an image in a div with javascript?

my js is not good, but I'm thinking I'm going to need to use the getElementbyId some think like:

if (a == ‘tick’)
document.getElementById(‘imageDiv’) = tick.gif
else
document.getElementById(‘imageDiv’) = cross.gif
<div id="imageDiv"></div>

but is does not work.

Answers:

Answer

Use this, it should work.

<script type="text/javascript">
function image(thisImg) {
    var img = document.createElement("IMG");
    img.src = "images/"+thisImg;
    document.getElementById('imageDiv').appendChild(img);
}
if (a == 'tick') {
    image('tick.gif');
} else {
    image('cross.gif');
}
</script>
<div id="imageDiv"></div>
Answer

Try this instead:

document.getElementById('imageDiv')
    .innerHTML = '<img src="imageName.png" />';

Or you can create image element dynamically like this:

var par = document.getElementById('imageDiv');
var img = document.createElement('img');
img.src = 'put path here';
par.appendChild(img);

Note also that you should use single quotes or double quotes not character for strings.


So here is how your code should be:

var imgName = a === 'tick' ? 'tick.gif' : 'cross.gif';
document.getElementById('imageDiv')
    .innerHTML = '<img src="' + imgName + '" />';

Or alternatively:

var imgName = a === 'tick' ? 'tick.gif' : 'cross.gif';
var par = document.getElementById('imageDiv');
var img = document.createElement('img');
img.src = imgName;
par.appendChild(img);

Or if you want apply your image to div background, then this is what you need:

var imgName = a === 'tick' ? 'tick.gif' : 'cross.gif';
document.getElementById('imageDiv').style.backgroundImage = 'url('+ imgName +')';
Answer

To display image in a div you must set it as background image:

document.getElementById(‘imageDiv’).style.backgroundImage = 'url(tick.gif)';
Answer
document.getElementById('imageDiv').innerHTML = 
 '<img src="' + (a == 'tick'?'tick':'cross') + '.gif">';

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.