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:
JS code:
- var img = document.createElement("img");
- img.src = "image.png";
- var src = document.getElementById("x");
- src.appendChild(img);
2nd way(using function):
- var img = new Image();
- var div = document.getElementById('x');
- img.onload = function() {
- div.innerHTML += '';
- };
- img.src = 'image.jpg';
CASE 2: If you want to insert an images in place of an existing image:
HTML code:
JS code:
- function ReplacingImage(){
- document.getElementById("x").src="image2.png"
- }
I think this may help you.