Why do I need to double-click? (JavaScript onclick event handler)

As a beginner in JavaScript and web development, I encountered a peculiar issue for the first time. In a simple example, I have two divs - left and right. The left div contains five images, while the right div is empty. There are two buttons - copy and delete, each with an onclick event handler. The Copy button copies the entire content of the left div and appends it to the right div. However, the delete button requires two clicks to remove a single image from the right div, making it necessary to click 10 times to delete the entire set. Why is this happening and what can I do to make the delete button remove an image with just one click?

Below is my complete code, tested on Microsoft Edge and Google Chrome, with the same result.

var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");


function Copy() {
  copy = theLeftSide.cloneNode(true);
  theRightSide.appendChild(copy);
}

function Delete() {
  copy.removeChild(copy.lastChild);
}
div {
  position: absolute;
  width: 670px;
  height: 520px;
  background: red
}
#rightSide {
  position: absolute;
  left: 670px;
  border-left: 1px solid black;
  background: black
}
<input type="button" value="Copy" onclick="Copy()">
<input type="button" value="delete" id="btn" onclick="Delete()">

<div id="leftSide" style="width:400px">
  <img src="smile.png" />
  <img src="smile.png" />
  <img src="smile.png" />
  <img src="smile.png" />
  <img src="smile.png" />
</div>

<div id="rightSide">

</div>

Answer №1

By default, most browsers add an empty text node between each element on your webpage. Your code is removing one of these empty nodes for every image, which is why it only works half of the time.

Here's a suggested modification:

function Remove(){
  var images = document.querySelectorAll('.rightSide img');
  container.removeChild(images[images.length-1]);
}

Answer №2

When it comes to removing nodes, make sure to target both text nodes and elements. To achieve this, consider using

copy.removeChild(copy.lastElementChild);

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

Dividers afloat - expanding current script with multiple additions

I am currently utilizing this website as a hub for showcasing my various web projects. The jsfiddle code provided in response to this particular inquiry is exactly what I need, however, I am unsure of how to have multiple divs moving simultaneously acros ...

ng-repeat hide all elements except the first one

Hello there! I'm currently working on rendering a form based on an API call. Using a couple of filters, I am able to hide all elements that have 'id' in the title and which equal 0. However, I do need to display the initial element Id. I tho ...

Changing a value to display with exactly 2 decimal places using jQuery

Similar Question: JavaScript: how to format a number with exactly two decimals Having successfully added values into a div with a total using some script, I attempt to convert those values into decimal numbers by dividing them by 100 to mimic currency ...

Can you modify a WordPress/WooCommerce title written in uppercase to display in proper capitalization?

My current project is centered around WordPress and utilizes WooCommerce as its e-commerce platform. I recently migrated products from an old site where the product titles were written in uppercase. At the moment, my HTML code for the product titles looks ...

Unusual anomalies observed in CSS navigation bar styling

During my CSS work on a navigation bar, I came across an unusual behavior. First Attempt: #nav li { display: inline-block; } #nav li { font-size: 1em; line-height: 40px; width: 120px; height: 40px; ...

Error message: "Attempting to assign a value to the 'size' property of an undefined object, despite the fact that

I recently started delving into NodeJS development and have configured Visual Studio Code for JavaScript development in node applications. During a Pluralsight lecture on Objects, the instructor demonstrated creating two scripts, dice.js and program.js, a ...

Adjust the jQuery resizable handlers on the fly

I am encountering an issue when attempting to change the handler on a resizable element. Initially, I used : $(line) .draggable({containment:"parent"}) .resizable({ containment:"parent", handles: "e, w" }); N ...

Incorrect script enqueue order in child theme of WordPress

Help needed with enqueuing a script in a WordPress child theme. Despite specifying Jquery dependency, the script is loaded before Jquery. The code in question: add_action( 'wp_enqueue_scripts', 'child_theme_scripts' ); function child_ ...

Bring the element into view by scrolling horizontally

I am facing a challenge with a list of floated left divs inside another div. This inner block of divs can be hovered over to move it left and right. Each inner div, known as 'events', has class names that include a specific year. Additionally, t ...

Is it possible to verify the presence of an ID with jQuery?

Is it possible to check for the existence of the id 'input-name' before assigning a value to the variable name using a line of code similar to this: var name = $('#input-name').attr("value"); In case the id 'input-name' does ...

What is the process of obtaining User properties through a URL and utilizing them as variables in JavaScript?

I need to retrieve the city properties: 918 using req.params.userMosque from the URL '/shalat/:userMosque'. I want to assign it to the variable city for customizing my API url request. However, it seems like it's not working as expected. I h ...

Using AJAX to set a session variable in PHP

Upon clicking a div, this JavaScript function is executed: $('.test').click(function(e) { e.preventDefault(); $.ajax({ url: 'ajax.php', type: 'POST', data: {"id": "<? ...

What can you tell me about Page Event functionality in Datatables?

Curious question -- I'm currently seeking a practical example of how to implement a 'page' event in a project utilizing DataTables. The provided documentation can be found here -- http://datatables.net/docs/DataTables/1.9.4/#page. Despite t ...

Refreshing a Nested Component Within a Parent Component in React

Currently, I am in the final stage of a small project where a Higher Order Component (HOC) is being utilized to display a basic Tinder-like application. The internal component is a class-based component containing its own fetch() call that presents user d ...

Using dynamic, deferred loading of scripts in JavaScript

Is it necessary to create a reference for a dynamic, lazy import that is used multiple times in a script? For example, if there are 2 event handlers importing different functions from the same module: /* index.js */ window.addEventListener("click", (e) =&g ...

Unable to administer AuthenticationController

I am attempting to inject a controller into my app.run function, but I keep encountering the following error: Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.2.10/$injector/unpr?p0=AuthenticationControllerProvider%20%3C-%20AuthenticationCon ...

Allow users to modify multiple rows in a customizable table with Flask

I am currently working on a web application that utilizes Flask/Python as the back-end with SQLite, and HTML/CSS/JS (Bootstrap) for the front-end. In one specific section of the application, users should be able to edit multiple fields simultaneously in a ...

Using regular expressions in JavaScript, we can separate a paragraph into individual sentences

Hey there! I'm currently working on a project that requires extracting sentences from a paragraph using regex in JavaScript. Unfortunately, my attempts to achieve this have resulted in syntax errors as I have tried methods used in other programming la ...

The PrimeNG FullCalendar feature seems to be malfunctioning and cannot be located

I've been working on integrating a FullCalendar module into my Angular 7 project. Despite following the steps provided in this link, I haven't had any luck: After executing this command: npm install <a href="/cdn-cgi/l/email-protection" clas ...

Utilizing AngularJS to dynamically bind input to a value with a filter and keep it updated

I'm facing an issue with an input element linked to an object property along with a filter. Even though I update the object.field programmatically, the displayed value in the input does not change, although the correct value is reflected in the DOM In ...