How can I insert an image into a div?

I currently have a div from my html file that has styling from my css file as well. When I try to append a .jpg picture from my .js file to the div, it doesn’t utilize the already defined styling. Am I appending the picture incorrectly? I don’t quite understand why it’s not using the defined styling.

var img = new Image();

img[0] = new Image();
img[0].src = '1.jpg';
img[1] = new Image();
img[1].src = '2.jpg';

document.getElementById('picture').append(img[0]);
#picture {
  height: 100px;
  width: 10px;
  border: 1px solid black;
}
<div id="picture">

</div>

2 thoughts on “How can I insert an image into a div?”

  1. append – Maybe you using jquery ?

    Default , you try "appendChild"

    <div id="picture"></div>
    <input type='button' onclick="foo" value='Add New Image'>
    <script>
    function foo()
    {
      var img=new Array(2);
      img[0]=new Image();
      img[0].src="1.jpg";
      document.getElementById('picture').appendChild(img[0]);
    }
    </script>
    

    If use Jquery

    <script>
    funcntion foo()
    {
      $("#picture").append("<img src='1.jpg'>");
    }
    </script>
    
    Reply
  2. First, a quickfix: Use an array []

    var img = [];
    
    img[0] = new Image();
    img[0].src = 'https://placehold.it/60x60/0bf';
    img[1] = new Image();
    img[1].src = 'https://placehold.it/60x60/fob';
    
    document.getElementById('picture').append(img[0], img[1]);
    #picture {
      height: 100px;
      width: 10px;
      border: 1px solid black;
    }
    <div id="picture">
    
    </div>

    Secondly: use an array of paths and use it to create your images without repeating much code:

    const images = [
      'https://placehold.it/60x60/0bf',
      'https://placehold.it/60x60/fob',
    ];
    
    const DF_images = images.reduce((DF, src) => {
      const Img = new Image();
      Img.src = src;
      DF.append(Img);
      return DF;
    }, new DocumentFragment());
    
    document.getElementById('picture').append(DF_images);
    #picture {
      height: 100px;
      width: 10px;
      border: 1px solid black;
    }
    <div id="picture">
    
    </div>
    Reply

Leave a Comment