Utilize DOM to attach a button onto an image

I am looking to add buttons onto images using DOM manipulation. Each image will have multiple buttons that, when clicked, will delete the image.

I am aiming for a functionality similar to this example - JSFiddle

This is the code I have attempted so far:

var div = document.createElement('div');
var parent = document.getElementById('images1');
var btn = document.createElement('input');
btn.type = 'button';
btn.className="multiple",
div.style.cssText = "position: relative; margin-bottom: 10px ; width: 100%;";
btn.style.cssText = " position: absolute; top: 10px; background-image: url(http://totravelistolearn.in/wp-content/themes/travel/images/cross-512.png); width: 20px; height: 20px; border: 0; background-size: 100%; background-repeat: no-repeat;";
btn.onclick = removeImage;
img = new Image();
img.style.display = 'block';
img.className = 'hi1';
img.style.cssText = 'height: 100px; width: 100px; position: relative;';
img.src = results[i];                       
div.appendChild(div);   
div.appendChild(img);                           
div.appendChild(btn);

Function to remove image -

function removeImage(){
    $$(this).prev("img").remove();  
    $$(this).remove();  
    div.parentNode.removeChild(div);
}

Answer №1

To achieve the desired functionality, it is recommended to use the class attribute instead of id. Utilizing the closest() method will help you accomplish this easily. Check out the DEMO for reference.

$('.myButton').click(function(){
    $(this).closest('.MyImage').remove();
});

Answer №2

When the button is clicked, you have the ability to delete the div that holds both the image and the button. This can be accomplished with the following code snippet:

$('.myButton').on('click', function() {
    $(this).closest('div.MyImage').remove(); 
});

It is not recommended to use the same id for multiple elements on a single page. In this example, I have changed them to classes and then proceeded with the removal. I would suggest following the same approach if it fits your specific scenario.

Check out the updated JSFiddle for reference.

Answer №3

From my understanding, this code has been written. Kindly review it once.

function createItem() {
    div = document.createElement("div");
    div.setAttribute("class", "parent");
    image = document.createElement("img");
    image.src = "http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg";
    image.style.width = "100%";
    btn = document.createElement("button");
    btn.setAttribute("class", "MyButton");
    var textnode = document.createTextNode("X");
    btn.appendChild(textnode);
    btn.style.position = "absolute";
    btn.style.left = "10px";
    btn.style.left = "10px";
    div.appendChild(image);
    div.appendChild(btn);
    div.style.width = "100px";
    div.style.height = "100px";
    div.style.overflow = "hidden";
    div.style.marginBottom = "10px";
    document.body.appendChild(div);
}
createItem();
createItem();
createItem();
parentDiv = document.getElementsByClassName("parent");
console.log(parentDiv.length);
buttonObject = document.getElementsByClassName("MyButton");
for (var i = 0; i < buttonObject.length; i++) {
    buttonObject[i].id = i;
    buttonObject[i].onclick = function() {
        myId = this.getAttribute("id");
        parentDiv[myId].remove()
    }
}

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

Having trouble connecting to JSTL in my JavaScript file

Currently, I am facing an issue with my JSTL code that is housed within a JavaScript file being included in my JSP page. The problem arises when I place the JSTL code inside a script within the JSP page - it works perfectly fine. However, if I move the s ...

Adding a local image to Firebase Storage in Angular5 / Ionic3

Uploading images is a breeze using the following method (select input file): import { AngularFireStorage } from 'angularfire2/storage'; @Component({ selector: 'app-root', template: '<div>' + '<input c ...

Is it possible to create a Nuxt.js static website that incorporates a dynamic single-page application built with Vue.js

Currently researching Static Site Generators for a client project, I discovered Vue.js and Nuxt.js, which appear promising. Given the choice between Vue.js and React, I lean towards Vue at the moment. The client's website consists of 120 pages with s ...

Using JavaScript to locate a child element within its parent

What is the most effective approach to locate a child element (using class or ID) of a specific parent element using only pure JavaScript without relying on jQuery or other frameworks? In this scenario, I am interested in finding child1 or child2 within p ...

Text overlay effect on hovering an image

I am struggling to add text to a photo and make the entire photo clickable with a link. I have already applied a darkening effect that I want to keep, but now I need to insert text on top of it. It is important for me to maintain the current dimensions and ...

Using jQuery to dynamically insert variables into CSS styles

I am attempting to use jQuery 3 to modify the CSS of a class and change the background color. My first step is converting an rgba color code (properties.color) to a hexadecimal code, which is functioning correctly. Next, I try to change the background co ...

My JavaScript array is not working with the stringify function

I am trying to encode my JavaScript array into JSON using stringify. Here is the code: params["margin_left"] = "fd"; params["text"] = "df"; params["margin_to_delete"] = "df"; console.info(params); When I check the output in Chrome console, it shows: [m ...

Exploring various endpoints using firestore Cloud Function

I am in the process of creating a versatile Cloud Function that can be executed on various endpoints. This is how my original Cloud Function looks: const functions = require('firebase-functions') const admin = require('firebase-admin' ...

Using only if-else statements and else-if conditions in JavaScript, arrange four numbers in order

How can I arrange 4 numbers in ascending order using only if-else and else-if statements in JavaScript without utilizing the sort function? ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

JavaScript-enhanced HTML form validation

I encountered a small glitch while working on simple form validation with JavaScript. I tried to catch the issue but have been unable to do so. Here is the code snippet, where the problem lies in the fact that the select list does not get validated and I ...

Aptana throws a fit over a script that's as empty as

Within Aptana, I am encountering an issue with the following line of code: <script type="text/javascript" charset="utf-8" src="js/jquery-1.7.2.js"></script> Alternatively, it could be written as: <script type="text/javascript" charset="ut ...

What is the best way to incorporate new elements into the DOM in order to allow users to share their comments

Can anyone help me with the code below? I have a text box and a comment section, along with a button to add comments. However, I need assistance with adding the posted comment below the comment section. Below is the code snippet: <div id="comments"&g ...

JavaScript issue: TypeError - Information.map is not a function. Learn how to properly use .map method

Currently, I am learning how to use CRUD in React with Express and Node. I have successfully inserted data into the database, but I encountered an error when trying to represent the data using .map. You can see the issue with <Input onClick="{getCR ...

Utilize javascript/jquery for transforming HTML table data to JSON

Whenever I click the "+" button, my table rows are dynamically generated. After populating the fields and clicking the submit button next to "+", the JSON data is displayed in the console, as shown in the image below. While generating the JSON data, I aim ...

Is Angular Translate susceptible to race conditions when using static files for multi-language support?

Currently utilizing angular translate with the static files loader for implementing multiple languages in my project. However, I've encountered a problem where the loading of language files sometimes takes longer than loading the actual view itself, l ...

I'm looking to create a unique combination of a line and bar chart. Any advice on how to

When I stretch my Scale like this determineDataLimits: function () { var min = Math.min.apply(null, this.chart.data.datasets[0].data) console.log(this) console.log(defaultConfigObject) Chart.options.scales.rightSide.ticks.min = function ...

New posts causing Ajax functionality to cease functioning

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#message').focus(); $('#message').keypr ...

Arrange the image in a way that flows smoothly with the text

I want to achieve the effect of having a picture of a Pen positioned behind the text "Create" on the left side. It looks good at full size, but the positioning gets messed up when the screen size is adjusted. How can I make it responsive so that the image ...

Using Strapi to run basic raw SQL queries with MySQL

Trying to execute this query in my test but struggling with the correct syntax. return strapi.connections.default.raw(` delete from nurses; delete from users_permissions_user;`); }); Since this is not using PostgreSQL and MySQL ...