Home > database >  Why is my Javascript not creating a div within a class?
Why is my Javascript not creating a div within a class?

Time:09-13

I'm taking a SkillShare course (I know, grain of salt with that) to create a responsive image gallery for my freelance art page. The current goal is to populate the page with images using Javascript. I'm trying to create a div called 'image' within a class called 'image-grid'; 'image' should contain a drawing from a folder called 'images'.

My pertinent HTML:

<body>

    <div >
        <h2 >Illustrations and Comics by Gwen</h2> 
    
    <div >
 
    </div>
    </div>
</body>

My Javscript:

const imagesList = [
    {
        imageUrl: "images/DyingToLive.png",
        title: "Dying to Live",
    },
];

const imageGrid = document.querySelector(".image-grid");

const populateImages = () => {
    imagesList.forEach((i) => {
        const image = document.createElement("div");
        div.classList.add("image");
        const img = document.createElement("img");
        img.src = i.imageUrl;
        img.alt = i.title;
        image.appendChild(img);
        imageGrid.appendChild(image);
    });
};

populateImages();

Teacher's version of the js: Teacher's version of js

Apologies if I'm missing something simple. My partner and I both went over it line by line for discrepancies. I have my own image name/title and I'm not using thumbnails so I went with imageUrl instead of thumbUrl. Apart from that, it looks identical to me.

The problem is that when I fire it up in my browser, there's no image, and when I view source, there's no sign of an 'image' div inside that image-grid class. Any direction would be greatly appreciated.

CodePudding user response:

Seems div.classList.add("image"); is useless,try to remove it

const imagesList = [
    {
        imageUrl: "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iXwouvL_DCbc/v0/150x-1.jpg",
        title: "Dying to Live",
    },
];

const imageGrid = document.querySelector(".image-grid");

const populateImages = () => {
    imagesList.forEach((i) => {
        const image = document.createElement("div");
        //div.classList.add("image");
        const img = document.createElement("img");
        img.src = i.imageUrl;
        img.alt = i.title;
        image.appendChild(img);
        imageGrid.appendChild(image);
    });
};

populateImages();
<body>

    <div >
        <h2 >Illustrations and Comics by Gwen</h2> 
    
    <div >
 
    </div>
    </div>
</body>

CodePudding user response:

change div.classList.add("image"); to image.classList.add("image");

  • Related