Search code examples
javascripthtmlimagesrccreateelement

getElementById() is null?


So I am trying to make a JavaScript program that will take a URL for an image and then put it onto the page while creating an <img> tag so that I can just continue pasting as many photos as I want. Here's the code:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Low-Budget Online Album</title>
<meta charset="utf-8">
<script>
    function init() {
        var button = document.getElementById("addButton");
        button.onclick = buttonClick;
    }
window.onload = init;

    function buttonClick() {
        var imageSource = document.getElementById("imageInput").value;
        if (imageSource == "") {
            alert("Please enter the source for an image.");
        }
        else {
            var newImage = document.createElement("img");
            var newSrc = document.getElementById("newImage").src= imageSource;
    
            imageInput.value = "";
        }
    }       
</script>
</head>
<body>
<input type="text" id="imageInput" size="40" placeholder="Image Source">
<input type="button" id="addButton" value="Add Image">
<img id="images" src="">
</img>
</body>
</html>

My problem is, is that when I put int a URL (or picture src from my PC) it says that TypeError: document.getElementById(...) is null, and points to line 20, being my

var newSrc = document.getElementById("newImage").src= imageSource;

line. Any ideas?


Solution

  • do you mean something like this:

    function init() {    
        var button = document.getElementById("addButton");
        button.onclick = buttonClick;    
    }
    window.onload = init;
    
    function buttonClick() {        
        var imageSource = document.getElementById("imageInput").value;
        if (imageSource == "") {
            alert("Please enter the source for an image.");
        }
        else {
            var newImage = document.createElement("img");
            newImage.src= imageSource;
            newImage.setAttribute("id", "newImage");
            imageInput.value = "";
            document.body.appendChild(newImage);
        }
    } 
    

    Demo:: jsFiddle