13

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.

1
  • @Black_Crown imageDiv is a div, setting src for it will not display any image. Commented Mar 7, 2012 at 6:46

4 Answers 4

12

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you have not only solve my problem but also provide me the axact code which i need to develop thanks.
11

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 +')';

Comments

4

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

document.getElementById(‘imageDiv’).style.backgroundImage = 'url(tick.gif)';

Comments

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

Comments

Your Answer

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