1

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'/>"
}

3 Answers 3

1
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);
}

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.