Why won't this 2nd .remove work?

Hi, I want to clear the images generated in the CAT GENERATOR code, but it doesn’t seem to work.

//AGED DAYS
function agedDays() {
 let birthYear = prompt('what year were you born');
 let agedDays = (2021 - birthYear) * 365; 
let h1 = document.createElement('h1');
let textAnswer = document.createTextNode('you are ' + agedDays + ' days old')
h1.setAttribute('id', 'agedDays')
h1.appendChild(textAnswer);
document.getElementById('flex-box-result').appendChild(h1);

 }
 function reset() {
     document.getElementById('agedDays').remove();
 }
//CAT GENERATOR

 function generateCat() {

    let image = document.createElement('img');
    let div = document.getElementById('catGen');
    image.src = "/images/grumpy-cat.jpg";
    div.appendChild(image);
 }
 function resetCat() {
    document.getElementById('generateCat').remove();
}

Thanks for your help here,

Jay

1 Like

Hi @JayGee007

You think you can share your full code in a platform link for other developers can test your code?

This will be easy for developers to understand your code and your issues.

1 Like

what should remove do? do you have the rest of your code and preferably a live preview like codepen or replit?

@ilenia

By looking at his code i made a test and i found out some points. I notice he have a first task of year born, by looking at it i make some assumptions.

  1. He is calling the prompt and saving the year born and then he try to remove the days old. with that example he want to do the same thing with an image.

  2. I made some test like this for the full code to work.

This is his HTML as assuming:

<!-- you are 13140 days old -->
<p id="flex-box-result"> 0 Days Old</p>
<a id="reset-btn" class="my-Btn" href="#">Reset days</a> 
//AGED DAYS
function agedDays() {
 let birthYear = prompt('what year were you born');
 let agedDays = (2021 - birthYear) * 365;
 
  // Grab your Element From the DOM
  const agedDayEl = document.getElementById('flex-box-result');
  // create h1 element
  let h1 = document.createElement('h1');
 
  let textAnswer = document.createTextNode('you are ' + agedDays + ' days old');
  h1.setAttribute('id', 'agedDays');
  console.log(h1);
  h1.appendChild(textAnswer);
  agedDayEl.innerHTML = 'You are  '+agedDays+'  Days Old ';
}
  agedDays();


// Reset field
const restBtnEl = document.getElementById('reset-btn');
// AddEventListener 
restBtnEl.addEventListener('click', reset);

// Function to reset
function reset(){
  const agedDays = document.getElementById('flex-box-result');
  agedDays.remove();

};

Note: The h1 really doesn’t make any sense, he could just reduce the code. Just followed what he got and make it a bit readable.

he wants the same thing to happen to the image removal (the second task).

thank you but I was hoping for an answer from OP, as they are who asked for help

Yes, i know right, I was curious about finding and trying out what he wanted, with the code example i posted he can really get the second task done. I will blur the spoiler for best practices.

Thanks, @ilenia for the follow-up.

Thanks for helping out everyone. I really appreciate it.

I managed to get this on to a domain for you to view and cut out some code and left just the cat image generator. The Age Calculator worked OK already.

james-gough.co.uk

I’ll have a look at the code you shared @ imendieta

Yes, it is supposed to remove the image of the cat so the program can run again.

At the moment, it deletes the image, but I can’t get it to work again without refreshing the browser.

Thanks again :slight_smile:

Ok I see. Just like @ilenia posted above can you share your full code in order for other developers to have a better understanding of what you want to accomplish.

Regarding the code i wrote will be good for you to take a look into it, will help you understand some new features you did not had in your original code post.

@JayGee007 I can see in console the following error:

Uncaught TypeError: document.getElementById(...) is null
    resetCat http://james-gough.co.uk/script/script.js:11
    onclick http://james-gough.co.uk/:1

Without seeing the source code is impossible to tell but my two cents are that you are deleting a div when removing, that is needed to generate the cat.

So the next invocation will fail.
Hope it helps :sparkles:

[EDIT]
According to the script that’s your code:

 function generateCat() {

    let image = document.createElement('img');
    let div = document.getElementById('catGen');
    image.src = "/images/grumpy-cat.jpg";
    div.appendChild(image);
 }
 function resetCat() {
    document.getElementById('catGen').remove();
}

You are definitely removing the catGen div that is assumed to be there when creating a new one.

I posted a link to a domain with the cat generator. Is it best to post it there or on here?

<div class="container-2">
    <div class="heading">
        <h1>Image Flex Cat Image Gen</h1>
    </div>
    <div class="flex-box-container1">
    <button class="btn btn-success" id="cat-gen-but" onclick="generateCat()">Generate Cat</button>
        <div>
            <button class="btn btn-danger" onclick="resetCat()">Start Again </button>
        </div>
    </div>
<div class="flex-box-container2" id="catGen">
</div>
</div>

//CAT GENERATOR

 function generateCat() {

    let image = document.createElement('img');
    let div = document.getElementById('catGen');
    image.src = "/images/grumpy-cat.jpg";
    div.appendChild(image);
 }
 function resetCat() {
    document.getElementById('catGen').remove();
}

Thanks

Thanks, @Marmiz. How do I delete just the image then? I tried using the ‘img’ and ‘image’ but neither worked.

You can simply get a NodeList list of all the images that are children of catGen.

document.querySelectorAll("div#catGen > img")
// NodeList []

Then iterate and delete.

@Marmiz would you be able to explain that a bit further please?

:slight_smile:

Sure thing @JayGee007.

With JS you have various options of selecting DOM nodes. Among which querySelectorAll.

You can pass any valid CSS selector string, and if there’s a match, this method will return all the elements in a NodeList.

In your case you can select all the images that are children of catGen

document.querySelectorAll("div#catGen > img")

Please refer to CSS selector in case you need a refresher of the above.

That method will return a NodeList[] with all that matches.

Then you can iterate and apply your logic.
For example:

document.querySelectorAll("div#catGen > img").forEach(img => img.remove())

Hope this helps :sparkles:

2 Likes

Thank you again @Marmiz

Hi @JayGee007

Thank you for providing the full code. Now developers will fully understand your issues or troubles you are having.

It seems @Marmiz find out a solution to the problem. The problem shows that a div was not there, it was erased by your previous function task to reset the img.

I found one of many options you can do this

Option 1:

You can do this easily without iterate in a loop by just grabbing the elements id catGen and then by using the innerHTML = ""; and set it to empty string.
but this option might not be suitable for high-performance applications. A more slower way in a browser.

function resetCat() {
  var catGenEl = document.getElementById('catGen');
  catGenEl.innerHTML = "";
  
}

Option 2:

This one is a more modern JS and it’s the best way of accomplishing this technique, I recommend using this over node.innerHTML = ""; A more faster way in the browser. It will remove the child of a parent element.

function resetCat(){
  const parentGen = document.getElementById("catGen")
    while (parentGen.firstChild) {
      parentGen.firstChild.remove()
    }
  
};

Hope this will help as well to understand different ways of writing the same code task.

Hi Everyone,

I have to say, I am so happy with the responses I have received from you all so far, esp @Marmiz and @imendieta with such comprehensive explanations.

I don’t have to tell you that i am just starting out with this. I will start a 4 month full time bootcamp in a few weeks time, but I am trying to learn as much as I can beforehand. Your answers and explanations give me hope that I will find good support along the way.

Have a great day

:slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.