Can You Dynamically Create A IMG element, and access it with document.GetElementById(name);

1.3k views Asked by At

This is my code, the issue is in the ldimg(); and the img(); ldimg(); creates the image element, and img(); gets it, but my alert() debugging test says cannot read source of null.

function ldimg(src, name) {
    var imageObj = document.createElement('img');
    imageObj.onload = function() {
        context.drawImage(imageObj, window.innerWidth + 100, window.innerHeight + 1, 1, 1);
    };
    imageObj.src = src;
    imageObj.id = name;
}

function img(name, x, y, width, height) {
    var image = document.getElementById(name);
    alert(image.src);
}
ldimg('bot.png', 'bot');

function Loop() {
    setTimeout(function() {
        img('bot', 100, 100, 100, 100);
        Loop();
    }, 16);
}
Loop();
</script> 
</html>
2

There are 2 answers

0
dgeare On

You could restructure the code to return the image from ldimg if you aren't intending to add it to the DOM.

function ldimg(src, name) {
    var imageObj = document.createElement('img');
    imageObj.onload = function() {
        context.drawImage(imageObj, window.innerWidth + 100, window.innerHeight + 1, 1, 1);
    };
    imageObj.src = src;
    imageObj.id = name;
    return imageObj;
}

function img(image, x, y, width, height) {
    alert(image.src);
}
var theImg = ldimg('bot.png', 'bot');

function Loop() {
    setTimeout(function() {
        img(theImg, 100, 100, 100, 100);
        Loop();
    }, 16);
}
Loop();
</script> 
</html>
0
Cory Kleiser On

You need to add the image to your DOM structure. To do that you can use appendChild as with the below example:

function ldimg(src, name) {
    var imageObj = document.createElement('img');
    imageObj.src = src;
    imageObj.id = name;
    var imageDiv = document.getElementById("imgDiv");
    imageDiv.appendChild(imageObj);
}

function img(name, x, y, width, height) {
    var image = document.getElementById(name);
    alert(image.src);
}
ldimg('http://thecatapi.com/api/images/get?format=src&type=gif', 'bot');
<div id="imgDiv"></div>

Also the setTimeout you have set up should be a setInterval this way you don't have to call the a function inside of itself. In the following example I have setInterval with a 10 second interval to make it slightly less annoying:

function ldimg(src, name) {
    var imageObj = document.createElement('img');
    imageObj.src = src;
    imageObj.id = name;
    var imageDiv = document.getElementById("imgDiv");
    imageDiv.appendChild(imageObj);
}

function img(name, x, y, width, height) {
    var image = document.getElementById(name);
    alert(image.src);
}
ldimg('http://thecatapi.com/api/images/get?format=src&type=gif', 'bot');

function Loop() {
    setInterval(function() {
        img('bot', 100, 100, 100, 100);
    }, 10000);
}
Loop();
<div id="imgDiv"></div>