Deletion of a custom function in JavaScript

I have written some basic code to generate and remove an image using functions. Specifically, I need help with removing the image created by the function Generate() when a button linked to the function Reset1() is clicked. Here's the code snippet for reference:

function Generate() {
    var image = document.createElement('img');
    var div = document.getElementById('flex-box-gen');
    image.src = "https://thecatapi.com/api/images/get?format=src&type=gif&size=small";
    div.appendChild(image);
}

function Reset1() {
    document.getElementById('Generate').remove();
}

Answer №1

To easily remove your image element in the second function, consider assigning an id to it and using that:

function generate() {
    var image=document.createElement("img");
    image.id = "image-01";
    ...
}

function reset() {
    var image = document.getElementById("image-01");
    var parent = image.parentNode;

    parent.removeChild(image);
}

If there are no other elements in your containing div, you can simply empty it:

function reset() {
    document.getElementById("flex-box-gen").innerHTML = "";
}

Answer №2

getElementById function is used to query a DOM element, not a javascript element.

If you only have one img in your flex-box-gen, you can do the following:

var imgs = document.querySelectorAll('#flex-box-gen img')
if(imgs.length > 0){
  imgs[0].remove();
}

Make sure to include a null-check in case the image has already been removed.

Answer №3

let newImageId = document.createElement('id');
newImageId.setAttribute('id', "Generate");
image.appendChild(newImageId);

Please include the above code snippet inside the generate function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

Discovered an issue with Sentry debugging where a lengthy string is being returned as undefined

We are currently in the process of developing an Angular 1.x application that utilizes Bootstrap components. Recently, we integrated Sentry debugging into our site and encountered the following error: 'PAPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDIN ...

The <h1> element is not responding to the style attribute

Exploring HTML as a beginner has led me to an interesting issue. I've been practicing my newfound skills on W3Schools' platform and everything was running smoothly until I encountered a discrepancy in how the code is rendered on Wordpress. The s ...

Exploring the Canvas with Full Element Panning, Minimap Included

Currently, I am working on incorporating a mini map onto my canvas that mirrors what is displayed on the main canvas. The main canvas includes zoom and pan functions. I have created a rectangular shape for the minimap to display the content of the canvas. ...

The submission of the Ajax form isn't functioning as expected

I have created a feedback form with an image submit button instead of the regular HTML submit button. When I try to submit the form, the "data:" value always returns as NULL. Can you help me identify the issue in my code? Here is the code snippet: The FOR ...

Customizing Attribute for Material UI TextField

I'm currently in the process of adding a custom data attribute to a TextField component like so: class TestTextField extends React.Component { componentDidMount() {console.log(this._input)} render() { return ( <TextField label= ...

Creating a hierarchical structure in HTML to represent a JSON object as a tree: techniques and best practices

I need help with displaying a nested JSON object that shows a one to many relationship between a parent node and its children in an organizational chart format using HTML. I have looked into utilizing Google Charts for this purpose, but I am unsure if it a ...

"Implementing responsive design with Bootstrap's carousel through media queries

I'm having some trouble creating a basic carousel using bootstrap because the images are not displaying full screen. Do I need to use media queries to achieve this and if so, how can I implement them? <div id="myCarousel" class="carousel slide" da ...

What could be causing a hydration error when utilizing a table in Next.js?

When attempting to use the tr tag in my code, I encountered an error message that reads: Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. import React from 'react' import {useS ...

The compare function in bcryptjs will result in a false output if the passwords include numerical

I have successfully used bcryptjs to hash my passwords during user registration. However, I am facing an issue with the bcrypt.compare function when attempting to log in. The function returns a false promise when passwords contain numbers or special charac ...

1 in every 3 divs in jQuery, chosen randomly

Hey there! I have a fun project in mind - programming a "Rock Paper Scissors" game with the computer. The only issue is figuring out how to make the computer choose a random object after I pick one of the 3 options. Here's what I've come up with ...

The parent font size is influenced by the font size of the child element

I am encountering an issue with my code that seems to be quite simple. Here is the code snippet: <p> <h3>Title is here</h3> This is the paragraph </p> Here is the CSS: h2 {font-size:2.3em;} h3 {font-size:1em;} p {font-size:0. ...

The React-FontAwesome icon is unable to display when a favicon has been set

I encountered an issue while using the react-fontawesome module to display brand icons. Whenever I set a favicon in <Head>...</Head> (imported from next/head), all the react-fontawesome icons disappear. Can someone please advise me on how to re ...

I need to know the right way to send a file encoded in Windows-1255 using Express

I'm currently developing an API that is responsible for generating text files. The purpose of this API is to support legacy software that specifically requires the use of Windows 1255 encoding for these files. To create the content of the file, I am r ...

When the content div is clicked within the overlay div, the popup will also close

I want to design a pop-up that features a container with a black background and some opacity, where the content of the popup is placed inside. Here's what I have in mind: <button (click)="showPopup = !showPopup">Open popup</button& ...

Show me a list of all the commands my bot has in discord.js

Recently, I developed a Discord bot using discord.js and attempted to create a help command that would display all available commands to the user. For example, one of the commands is avatar.js module.exports.run = async(bot, message, args) => { le ...

jQuery - harnessing the power of JavaScript events such as "dragover"

I have a JavaScript function that includes an event listener for 'dragover'. Here is the code snippet: document.getElementById("someID").addEventListener("dragover", function(){ //Add your logic here }, fa ...

Nuxt.js has exceeded the maximum call stack size

Recently, I started working on a nuxt.js/vue project using a pre-built starter template. However, I have been encountering numerous error messages such as "Maximum call stack size exceeded." It's quite challenging to pinpoint the exact source of these ...

Is it necessary for me to include body, html at the beginning of my CSS code?

For all of my pages, I have been including the following code at the top. body { color: #333333; font-family: Arial,sans-serif; font-size: 0.95em; line-height: 1.15; } However, a colleague of mine has informed me that I only need to targ ...

Unexpected interactions between Socket.io and React using hooks

Currently, I am delving into the world of Socket.io with React utilizing Hooks. My goal is to create a timer that starts upon pressing the start button, and then every second, send the current time in the state to the server using socket.io. The server co ...