I want to add an image with class name to my div using pure Java Script. How can i do that? Here is my JS code.
function show(){
var y = document.getElementById("gallery1");
y.innerHTML="<img src='css/images1/img/img4.jpg'/>"
}
function show(){
var y = document.getElementById("gallery1");
y.innerHTML= y.innerHTML + "<img src='css/images1/img/img4.jpg' class='specifyclassnamehere'/>";
}
Hope you're trying to append the image. So you must add it to the inner HTML.
Another option would be:
function show(){
var y = document.getElementById("gallery1"),
image = document.createElement("img");
image.src= "css/images1/img/img4.jpg";
image.setAttribute("class","specifyclassnamehere");
y.appendChild(image);
}
If you want to add an image with a class attribute, you can either create an image element and append it to your div (or parent element):
function show(){
var y = document.getElementById("gallery1");
var image = new Image();
image.src = "css/images1/img/img4.jpg";
image.setAttribute("class","myclass");
y.appendChild(image);
}
Or even include directly into your img tag, like this:
<img class="myclass" src='css/images1/img/img4.jpg'/>
Here is a Fiddle, see if it helps.
You can try this
function show(){
var y = document.getElementById("gallery1"),
tempDiv = document.createElement("div"),
image = document.createElement("image");
console.log(y);
image.setAttribute('src',"https://www.google.fr/images/srpr/logo11w.png");
image.setAttribute("class","myclass");
tempDiv.appendChild(image);
console.log(tempDiv);
y.innerHTML=tempDiv.innerHTML
}
<div id="gallery1"></div>
<a href="" onClick="show(); return false">Click me</a>