JS document.createElement function, CSS not working as intended

Hi Campers,

I am working on a page that lists a bunch of paintings and some info under each painting. I am using the function below to create the DOM elements from an array of objects.

I want the page to look like this:

But instead it looks like:

I am using the same CSS on this Gallery page as I am on my Artworks page. The only difference I see is that the Artworks page is manually written HTML and the Gallery page is generated from my JS.

What am I missing here?

  let createPaintingElements = function(p){
    // Object with all the paintings and info
    var paintingList = document.getElementById("paintingList");
    // Fragment to store the elements before "flushing"
    var myDF = document.createDocumentFragment();
    // Parent div in the fragment, all divs append to it
    var galleryDiv = document.createElement("div");
    galleryDiv.className += ("galleryDiv")

    // Loop through the paintings array of objects
    for(pi of paintings){
      //img src, class name
      var img = document.createElement("img");
      img.className += ("galleryPicImg")
      img.src = pi.img;
      // Info text box at bottom of img
      var infoDiv = document.createElement("div");
      infoDiv.className = ("infoDiv");
        var title = document.createElement("div");
        title.className = ("galleryPicTitle")
        title.textContent = pi.title;
        var size = document.createElement("div");
        size.className = ("galleryPicSize")
        size.textContent = pi.size;
        var price = document.createElement("div");
        price.className = ("galleryPicPrice")
        price.textContent = pi.price;


Full Code:


In your code you add one div with class galleryDiv. Then You add a bunch of images without wrapper. My guess is that galleryDiv is supposed to be the wrapper. That is how you did it on the other page as well and you gave it the same styling as well.
So create a a new div galleryDiv inside your loop and then append it.

1 Like

Move the following to the beginning of the for loop.

    // Parent div in the fragment, all divs append to it
    var galleryDiv = document.createElement("div");
    galleryDiv.className += ("galleryDiv")

Move the following to the end of the for loop.


Thank you both. Today was my first time using createElement. I see what was wrong now. In retrospect I should have realized this, it was right in front of my face!