What is the simplest method to remove numbered images after they have been clicked on?

I am working with a simple code that displays images of numbers 1-10 on the screen (named 1.jpg, 2.jpg, etc.). A random number is generated and when the correct image is clicked, a prompt appears. However, I want the incorrect image to disappear when clicked. I can achieve this using separate functions for each image, but I'm looking for the most efficient way to do it all in one function. Can anyone provide some guidance?

Answer №1

To better assist you, it would be beneficial to see snippets of your code in order to provide a thorough response here.

If your HTML structure resembles something like this (although steps could be omitted if there is an 'id' in your 'img' tags), the following JavaScript solution may work:

<div id="image-wrapper">
   <img src="1.jpg">
   <img src="2.jpg">
   <img src="3.jpg">
   ...
</div>

With plain JavaScript, you can implement the following approach:

var rnd = ... //generate a random number
document.querySelectorAll("img").forEach(img => {
   img.onclick = () => {
      let src = img.src;
      src = src.split("/"); 
      src = src[src.length - 1]; 
      src = src.split("."); 
      src = src[0];
      src = parseInt(src); 
      if(rnd !== src) {
         img.parentElement.removeChild(img);
      } else {
         alert("foo"); 
      }
   };
});

Explanation: By using document.querySelectorAll, you can select multiple HTML nodes and iterate over them using array.forEach. Registering an onclick event on each image, extracting the filename from the source, comparing it to a random number, and manipulating the DOM accordingly.

I hope this guidance helps. For further assistance, please enrich your query with additional details :)

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

Add a square div in every direction around the existing content in an HTML file

Begin by locating square number 1. Once you press the + symbol above square 1, square 2 will appear. From there, you can click the + on the right side of square 2 to reveal square 3. Is it possible to achieve this sequence? If so, what is the best way to ...

Tips for retrieving HTML code from a URL after JavaScript has loaded

I am currently working on developing an app that retrieves data from a website. Unfortunately, the website does not offer an API for this purpose, so I decided to create my own solution. Here is the issue at hand: I have written the following code to extr ...

Change the class of the div when the first div is selected

My goal is to switch the class of the #klapp element (from .klapp to .klappe) whenever a click event happens inside the #label-it container, including when the #klapp element itself is clicked. The challenge is that I am not able to use unique IDs for each ...

To retrieve the first td element by clicking a button within the corresponding row using JQuery

This may seem like a straightforward inquiry, but despite my best efforts, I have been unable to find a solution. I am looking to create a function that will allow me to click a button located in the 3rd td element and display the text from the first td e ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

I am looking to dynamically assign CSS classes to elements in my HTML document. Additionally, my project utilizes Angular 5 and Bootstrap version 3.3.7

I am currently in the process of generating a table using data obtained from a JSON. Due to the potential for a large amount of data, I have implemented a loop to create all the rows within the table. My goal is to enable users to click on any specific row ...

Verifying that phone numbers and email addresses are accurate prior to submitting the form

As a PHP newcomer, I apologize if my question appears somewhat naive. Currently, I am working on a contact form that is functioning well, but I need to implement validation for two specific fields: the phone number and the email address. For the phone numb ...

Guide on uploading multiple images using AJAX and jQuery

Here is the code snippet I am currently working on, which allows users to upload one or multiple files and delete them. All the file data is stored in the variable form_data. Unfortunately, I have not been successful in getting the file upload functionali ...

Tips on retrieving JavaScript output within an AngularJS model

When I bind the result date to an input text based on the input id, the input value is not saving in the ng model of Angular script. <input type="text" class="form-control" maxlength="10" ng-model="EmployeeSave.HijriDate" onclick="showCal2();" ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

Tips for creating a validation section in a CRUD application using React.js

I have been working on developing a CRUD app using ReactJS. However, I am facing some challenges with the validation process as it does not seem to be working correctly and I am not receiving any results. As a beginner in this field, I would greatly apprec ...

Is there a way to utilize and incorporate Functions from a separate file within an API Server file?

I have integrated ReactJS, Firebase, and React Redux into my project. https://github.com/oguzdelioglu/reactPress Currently, I am displaying data from Firestore by utilizing Functions in https://github.com/oguzdelioglu/reactPress/blob/master/src/services/ ...

Executing Bower installation within a corporate proxy network

Encountering Error : ECONNREFUSED Request to https://bower.herokuapp.com/packages/bootstrap-datepicker failed: connect ECONNREFUSED while attempting Bower Install from Package Manager Console. I came across suggestions in a different discussion on how to ...

Expanding a modest background image with CSS styling

I'm struggling to grasp the correct CSS syntax for scaling or expanding an image. Despite trying multiple approaches, I can't seem to get it to function properly. The current code in use is: background:url(../images/body_bg1.jpg) fixed repeat- ...

Breaking down an array into function arguments in TypeScript/JavaScript

I am working with an array of object instances that have different types. var instances: any = []; instances["Object1"] = new TypeA(); instances["ObjectB"] = new TypeB(); Each type has its own methods with unique names and varying numbers of arguments. I ...

What is the best method for storing and accessing audio files that users upload in my MERN application?

I am developing a MERN application and am looking to implement a feature that allows users to upload audio files. I have read that storing the files directly in the database or within a folder inside the app is not recommended. I need a solution that en ...

Using Node.js and Multer to update a file uploaded to MongoDB

I have a website that allows users to upload files, but I also want them to be able to edit those files. This would involve the user pressing "edit" and replacing the existing file in the database with a new one. Normally, you can use findByIdAndUpdate for ...

Reposition TorusGeometry to align with Coplanar Points

My three.js scene consists of 3 coplanar points and a torus geometry. I am looking for a way to transform the torus geometry so that it appears to be resting on the coplanar points. How can this be achieved in three.js? You can view an example of this sce ...

Generating dynamic HTML content in React using a variable within a string

Currently, I am utilizing TypeScript in a React application. I am receiving the following data from an API: a) a list of variable names ["name", "surname"] b) several strings in simple HTML form with variables "<p>Hello, ho ...

What is the snapping feature of the jQuery Mobile slider?

I've been diving into various sources for the past couple of hours, attempting to implement code snippets claiming to enable snapping functionality on a slider component. I'm facing doubts about the feasibility of achieving this with the jQuery M ...