Search code examples
javascripthtmlchild-process

How do you make a child img show an image?


I am trying to make a child element appear when you click a button but the child element is an image but the image won't appear, only the element will. I have recycled some code from a different project and that might be the issue but I'm not too sure.

I originally had the code to create an <img> child but then it would say that I couldn't append it. I have tried changing the code to not append the child but that only ends up with another error. (In advance, sorry if the name of the image seems a bit immature but it's named that way to keep myself organized. And sorry if the formatting is off, I'm a bit new to the site.) Here's the code if you want to check it out;

function G() {
    var B1 = src="Intro-v4PPSs.jpg"
    const para = document.createElement("img");
    const node = document.createAttribute(B1);
    para.appendChild(node);
    const element = document.getElementById("demo");
    element.appendChild(para);
}

Solution

  • Your function should be like this as below

    function G() {
        const para = document.createElement("img");
        para.src = "Intro-v4PPSs.jpg";
        const element = document.getElementById("demo");
        element.appendChild(para);
    }