3

Now I have this:

<script>
 function load() { 
 var el = document.getElementById('load');
 el.innerHTML='<img src=\"load.png\">'; }
</script>

And the html:

<input type="submit" onclick="javascript:load();"> 
<span id="load"> </span>

but that doesn't work, because i may not put < and > within the el.innerHTML=''. Does anyone know an alternative?

TIA

  • 1
    your script is working for me, at least in chrome, see this [fiddle](http://jsfiddle.net/Bwp8U/) – Michal Klouda Nov 05 '12 at 15:51
  • please find following code @ http://jsfiddle.net/umUnn/ – Ashish Kasma Nov 05 '12 at 15:55
  • Check out `createElement` function of the `document` object; i.e. `document.createElement("img")`. See the OP of this question [http://stackoverflow.com/questions/226847/what-is-the-best-javascript-code-to-create-an-img-element](http://stackoverflow.com/questions/226847/what-is-the-best-javascript-code-to-create-an-img-element) – cbayram Nov 05 '12 at 15:55

4 Answers4

2

The whole point of innerHTML is that you can use < and > inside it. You have some pointless escaping of quotes, and the cargo-cult javascript: label, but the script works.

It probably just looks like it is failing because the form submits and the browser leaves the page before the image loads.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • then how should I write it? The escaping was because first, I didn't make a function but just wrote all in the onClick – user1649795 Nov 05 '12 at 16:36
0

Use jQuery!

<button id="button">Click</button>

$(document).ready(function(){
    $("#button").click(function(){
        $("#load").append("<img src='\load.png\'/>");
    });
});
pmandell
  • 4,288
  • 17
  • 21
0

You should create the element using createElement() method and then append it to your container:

var el = document.getElementById('load');
var img = document.createElement('img');
img.src = 'test.png';
el.appendChild(img);
alert(el.innerHTML);

See this DEMO.

Michal Klouda
  • 14,263
  • 7
  • 53
  • 77
-1

You might try this:

javascript:

 function showImage(){
     document.getElementById('load').style.display = 'block';
  }

html:

 <input type="submit" onclick="showImage();">
 <span id="load" style="display:none;"><img src="load.png"></span>
Maxim VA
  • 370
  • 1
  • 3
  • 16
  • The HTML is invalid too. You shouldn't escape `"` with `\`. – Quentin Nov 05 '12 at 15:57
  • seriously, i just copied that line from the given javascript piece of the question. damn – Maxim VA Nov 05 '12 at 15:58
  • And while this is a different approach to the problem … you haven't explained what benefits doing it this way have over the version in the question. – Quentin Nov 05 '12 at 15:59
  • "but that doesn't work" I just wrote something that would work, it's up to other people to say something better if they now it better, like you do.. – Maxim VA Nov 05 '12 at 16:01