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

What is the methodology behind stackoverflow's implementation of comments functionality?

I am looking to implement a feature comparable to the comment system on Stack Overflow for this website. The idea is to enable users to type in a text, click submit, and instantly see it displayed on the page without having to navigate away. It has to be ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

A set of four responsive divs arranged vertically

Confession time... I'm facing a challenge with this task... I'm attempting to create a responsive page with 4 stacked divs. Here are the guidelines for each div: The header div: The text should be at the bottom, serving as a slogan placed clo ...

Custom input field in Material UI not communicating properly with Redux form

I am currently utilizing Material UI and React to implement a custom input field. While using redux form for form validation, I have encountered an issue where the onBlur and onFocus events are not being dispatched successfully. Interestingly, if I switch ...

Filter out the selection choice that begins with 'aa' in the drop-down menu

Here is a select field with various options: <select id="sel"> <option value="1">aadkdo</option> <option value="2">sdsdf</option> <option value="3">aasdfsddkdo</option> <option value="4"> ...

Troubleshooting border problems with Bootstrap 3 tables

Recently, I encountered a problem with the Bootstrap 3 table-bordered where the right border was not showing up. Below is the code snippet of my table: <table class="table table-bordered table-hover"> ... </table> Upon inspecting the table vi ...

Learn how to reposition the mat-option easily

I have an angular app with an autocomplete field that I need to adjust the position of. I have consulted the official documentation under the method updatePosition, which states: "Updates the position of the autocomplete suggestion panel to ensure that it ...

A mistake has been identified: The object could potentially be 'null'. TS2531 for window.document

This is my first time integrating TypeScript into my project. When attempting to access something using window.document.getElementById(), I keep encountering the error: Type error: Object is possibly 'null'. TS2531 I've looked online for ...

The Node.js application is up and running on the Node server, but unfortunately, no output is

Greetings, I am a beginner in nodejs. var io = require('socket.io').listen(server); users = []; connections = []; server.listen(process.env.PORT || 3000); console.log('server running....on Pro'); app.get ('/', function(re ...

Tips for creating a responsive iframe without relying on aspect ratio assumptions

Is there a way to create a responsive iframe without relying on a fixed aspect ratio? The width and height of the content are unknown until rendering. Keep in mind, using Javascript is an option. For instance: <div id="iframe-container"> <i ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

utilizing angularjs and bootstrap to manage multiple button models

Recently delved into learning angularjs and bootstrap. Found a tutorial on creating buttons. <div ng-controller="ButtonsCtrl"> <h4>Checkbox</h4> <pre>{{checkModel}}</pre> <div> <button type="butto ...

Manipulating the DOM results in the SWF being reloaded

Currently, I am utilizing jQuery to insert an SWF into the DOM. However, when the SWF loads and I attempt to clone or wrap it, the SWF ends up reloading. Preventing this reload is crucial for me. Here's an example: $('#test9').before(&apo ...

Trie-based autocomplete functionality

I am currently creating an auto-completion script and I'm considering utilizing a trie data structure. My main concern is that I want all possible matches to be returned. For instance, when I type in the letter r, I expect to see all entries beginning ...

The fixed background-attachment feature does not function properly in Chrome when it is contained within a scrolling div

Essentially, if a background image is placed within a scrolling div, it will no longer remain fixed and will revert back to scrolling: CSS: <div class="wrapper"> <span></span> </div> HTML: html, body{ width: 100%; height: ...

AngularJS: Toggle footer visibility with custom message

My goal is to develop an Angular app using Intel XDK with 3 page scripts in index.html, each having a separate footer. The requirement is for the footer and its message to display and hide every 5 seconds when running each page. app.js app.controller(&ap ...

When the window is resized, the text and images become jumbled and distorted

As a beginner in CSS, I am encountering an issue where the text and images on my website get distorted when I resize the window. How can I resolve this? HTML <img src="images\titles_03.jpg" class="tt1" > <img src="images\titles_05.jpg ...

Troubleshooting a minor JavaScript loop problem

I am facing an issue with my script that retrieves data from a database. Currently, when the search() function is called by clicking a button, only one result is displayed in a new div. How can I ensure that a new div is created for each result found, rath ...

Preventing jQuery parser from turning arrays into objects

My JavaScript data file has the following structure: data = { items : [ {name: 'ABC'}, {name: 'CDF'} ] } After passing this data to $.ajax(type: 'POST', data: data), the converted data appears like this: it ...

Mastering the art of utilizing the LESS preprocessor with React Create-React-APP

Is it possible to implement the LESS preprocessor in my create-react-app project? In my React code, I have the following: ReactDOM.render( <form> <input type="email" data-info="Enter Email" pattern="/\S+@\S+\.\S+/ ...