QNA > H > How To Insert An Image In Javascript

How to insert an image in Javascript

To insert an image into HTML using Javascript I recommend the following ways:

There are two possible cases:

CASE 1: If you want to add a new image to a div:

1st way:

HTML code:

  1.  

JS code:

  1. var img = document.createElement("img"); 
  2.  
  3. img.src = "image.png"; 
  4. var src = document.getElementById("x"); 
  5.  
  6. src.appendChild(img); 

2nd way(using function):

  1. var img = new Image(); 
  2. var div = document.getElementById('x'); 
  3.  
  4.  
  5. img.onload = function() { 
  6.  
  7. div.innerHTML += ''+img.src+'';  
  8.  
  9. }; 
  10.  
  11.  
  12. img.src = 'image.jpg'; 

CASE 2: If you want to insert an images in place of an existing image:

HTML code:

  1. image1.png
     

JS code:

  1. function ReplacingImage(){ 
  2.  
  3. document.getElementById("x").src="image2.png" 
  4.  

I think this may help you.

Di Hay Latouf

Se un cellulare non ha una carta SIM, come può fare chiamate d'emergenza? :: Qual è meglio, OPPO o Samsung?
Link utili