views:

41

answers:

4

I have a div tag

<div id="img"> <div>

and a script in page

<script type="text/javascript">
 function img(){
   document.getElementById('img').innerHTML="<a href="/lime/link.html"><img src="/lime/img.png"></a>";}
</script>

how to put the image on the div with link on pageload?

A: 

You have " characters inside a "-string.
Therefore, the string ends at the first ", and the rest of the line becomes a syntax error.

You should use ' instead of " to create the string, like this:

'<a href="/lime/link.html"><img src="/lime/img.png"></a>'

Also, the code can only work if the img element has already been parsed.
If the <script> block appears before the <div> tag, you'll need to execute the code in the onload event.

Finally, your example defines a function, but never calls the function.

To execute the code, you need to call the function.

SLaks
+2  A: 

Use window.onload for that:

<script type="text/javascript">
    window.onload = function(){
      document.getElementById('img').innerHTML='<a href="/lime/link.html"><img src="/lime/img.png"></a>';
    };
</script>

Note: You were having quotes mis-match problem, I have fixed that too :)

Sarfraz
A: 

Use the onload-event

function appendHref() {
    document.getElementById('img').innerHTML="<a href=\"/lime/link.html\"><img src=\"/lime/img.png\"></a>";
}

if (window.addEventListener){      
    window.addEventListener('load', function(e) {appendHref();}, false);} 
else if (window.attachEvent){     
    window.attachEvent('onload', function(e) {appendHref();}); 
}
nikc
A: 

Add window.onload=img; to your script, outside of the function img (){}

Tumharyyaaden