0

I'm learning to generate and remove one image at a time using DOM and I'm unable to understand this error. It works fine till I add the if statement. I've look thru similar post on stack overflow but still can't grasp it. My code as follows:

HTML

<div id="imageContainer"> <!-- <img src="/image/bananas.jpg"> --> </div> 

Javascript

let images = [ { image_name: 'bananas.jpg', number_of_items: 6, }, { image_name: 'birthday candles.jpg', number_of_items: 7, }, { image_name: 'blocks.jpg', number_of_items: 6, }, { image_name: 'brushes.jpg', number_of_items: 7, }] let generate = () => { let randomNum = Math.floor(Math.random() * images.length); let imageGenerated = images[randomNum].image_name; let imageContainer = document.getElementById("imageContainer"); if (imageContainer.hasChildNodes()) { imageContainer.removeChild(imageContainer.firstElementChild); } let img = document.createElement("img"); img.src = "image/" + imageGenerated; imageContainer.appendChild(img); }; let timer = () => { setInterval(generate, 3000); }; 
1
  • hasChildNodes returns true iff the parent has childNodes, not iff it has children. You’re attempting to remove the firstElementChild, which may not exist (whereas the firstChild does). Commented Jul 8, 2021 at 5:02

1 Answer 1

2

Your problem is that hasChildNodes checks for any type of node and the comment is a node.

To check for children use element.children, it returns an array-like object of all child elements.

if (imageContainer.children.length) { imageContainer.removeChild(imageContainer.children[0]; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.