<html>
<head>
<title> OLL </title>
</head>
<body>
<script type=text/javascript>
//Loads Images
//img.src = 'path/to/image.jpg';
var img = new Image();
var div = document.getElementById('foo');
img.onload = function() {
div.appendChild(img);
};
//img.src = 'path/to/image.jpg';
img.src = 'bone.jpg';
</script>
</body>
</html>
Whenever I open it up on chrome it doesn't show bone.jpg
bone.jpg
is in the same folder as the html file and when I open up the console it shows
Cannot read property 'appendChild' of null at Image.img.onload
I'm new to JavaScript so please make your response as simplified as possible.
You need a div with the id foo
in your markup to append to:
<html>
<head>
<title> OLL </title>
</head>
<body>
<div id="foo"></div>
<script type=text/javascript>
var img = new Image();
var div = document.getElementById('foo');
img.onload = function() { div.appendChild(img); };
img.src = 'bone.jpg';
</script>
</body>
</html>
You need to add a <div>
with the id foo
to your HTML markup, otherwise your script can't find an element with such an id and return null
, to which cannot be appended to:
[...]
<body>
<div id="foo"></div>
<script type=text/javascript>
[...]
In full code:
<html> <head> <title> OLL </title> </head> <body> <div id="foo"></div> <script type=text/javascript> var img = new Image(); var div = document.getElementById('foo'); img.onload = function() { div.appendChild(img); }; img.src = 'bone.jpg'; </script> </body> </html>
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.