Search code examples
javascripthtmlinnerhtmlappendchildcreateelement

Insert Image to div upon click


I want to be able to add an image to this div once the button is clicked and a check box is checked. I have already confirmed that the checkbox portion works properly, but can't get the photo to go into the div.

Here is what I currently have:

<button id="show_button">Show System</button>
<div class="box" id="AC1"></div>
<script>
var show_button = document.getElementById('show_button');
var show = function() {
    // AC Relevant Components;
    var ch_mGT = document.getElementById('mGT').checked;
    // Set AC1
    if (ch_mGT) {
         var AC1_html = "<img src='http://localhost/....png' alt='Micro Turbine' 
         height='50px'>";
         document.getElementById("AC1").innerHTML(AC1_html);
    }
}
show_button.addEventListener("click",show);
</script>

I also have already tried:

var AC1_img = document.createElement("img");
AC1_img.src = 'http://localhost/....png'
document.getElementById('AC1').appendChild(AC1_img);

Solution

  • You said you tried using appendElement, but it seems to be working in the below example.

    var show_button = document.getElementById('show_button');
    var show = function() {
     var ch_mGT = document.getElementById('mGT').checked;
     var AC1_img = document.createElement('img')
         AC1_img.src="https://i.ytimg.com/vi/r4Hve6fZ7ik/maxresdefault.jpg"
         AC1_img.style.height = "50px"
         AC1_img.alt = 'Micro Turbine'
    	 if (ch_mGT) {
    	   document.getElementById("AC1").appendChild(AC1_img)
       }
    }
    show_button.addEventListener("click",show);
    <div class="box" id="AC1"></div>
    <input type="checkbox" id="mGT">
    <button id="show_button">Show System</button>