简体   繁体   中英

I am trying to add an image to HTML using javascript but there is no content?

When I try to add the Image with javascript, it displays the boarder of the image but there is no content inside. It is just an empty blank box. Any ideas?

Javascript:

var img=document.createElement("img");
img.src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
var src = document.getElementById("gameboard");
src.appendChild(img);

HTML:

<body>
  <div>
    <img id="gameboard">
  </div>
</body>

Jsfiddle: https://jsfiddle.net/bj5d6t7k/1/

You are trying to append image inside another image which is not allowed. Simply set the src attribute of the existing image:

 var img=document.getElementById("gameboard"); img.src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
 <body> <div> <img id="gameboard"> </div> </body>

OR: If you want to create the element and append that with Node.appendChild()

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.

 var img=document.createElement("img"); img.src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"; var gamecontiner = document.getElementById("gamecontiner"); gamecontiner.appendChild(img);
 <body> <div id="gamecontiner"> </div> </body>

Please check this below code

var img = new Image();
var div = document.getElementById('gameboard');

img.onload = function() {
div.appendChild(img);
};

img.src = 'path/to/image.jpg' 

As per your code you are appending one image above another one

After load document then access node. Give id to div tag. See below,

<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        var img = document.createElement("img");
        img.src = "https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
        var srcimg = document.getElementById("gameboard");
        srcimg.appendChild(img);
     });
</script>

<body>
    <div id="gameboard">
    </div>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM