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.
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.
Share Improve this question asked Mar 7, 2012 at 6:39 user1234315user1234315 1 |4 Answers
Reset to default 12Use 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>
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 +')';
To display image in a div you must set it as background image:
document.getElementById(‘imageDiv’).style.backgroundImage = 'url(tick.gif)';
document.getElementById('imageDiv').innerHTML =
'<img src="' + (a == 'tick'?'tick':'cross') + '.gif">';
imageDiv
is a div, setting src for it will not display any image. – kirilloid Commented Mar 7, 2012 at 6:46