1

I have a loop that goes through a collection of folders and displays images. I can't figure out how to just make it display just the images that are in the folder, so the hacky way I came up with is to just have the loop iterate through the folder 100 times, regardless of whether there is 1 or 100 images in it.

This results in having many broken images in my carousel because, of course, there's nothing there after the iteration is finished going through the images that do exist.

I'm trying to figure out, through React, how to remove those broken images by removing them from the DOM using removeChild(), but I keep getting errors thrown at me.

I don't want to go to using "display: none;" or "visible: hidden;" in CSS because that still enables people to keep clicking through the carousel until they end at the 100th iteration. Though if there is a way, through Javascript, to just send the user back to the beginning of the carousel in the event of a 404, I'd be willing to use that, as well.

This is my code:

const thumbnailErr = () => {
 let node = document.getElementById("image-gallery-thumbnail");
 if (node.parentNode) {
   node.parentNode.removeChild(node);
   }
 }

When I call this function, it throws me this error:

TypeError: Cannot read property 'parentNode' of null

I can't imagine this is the best way to do this, but it's the only promising way that I've found so far as a workaround. What I'm gathering is that removeChild() is expecting there to be something to remove, and since the image is 404, it's giving this error saying it doesn't have anything to remove. Problem is that the broken images are still displaying in the carousel.

Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
rvor
  • 87
  • 1
  • 7
  • The problem is that `image-gallery-thumbnail` element apparently does not exist on the page at all - whether an image's src results in 404 or not will have no effect here – CertainPerformance Aug 26 '19 at 06:20
  • I just found out why it was throwing me this error in particular. It's because it's a class name in CSS; not an ID. When I switched it to "getElementByClassName," I now get this error: TypeError: document.getElementByClassName is not a function – rvor Aug 26 '19 at 06:23
  • There is no such method as `getElementByClassName `. There is, however, a method named `getElementsByClassName `. But since you just want a single element, use `querySelector` instead – CertainPerformance Aug 26 '19 at 06:24
  • Yeah, using querySelector just brings me back to the same "TypeError: Cannot read property 'parentNode' of null" – rvor Aug 26 '19 at 06:32

0 Answers0