What could be causing the closest() method in my JavaScript code to not locate the nearest class?

I've encountered an issue while dynamically creating new classes with input fields in my project. For some reason, when I try to remove a previous row, nothing happens. Can anyone help me troubleshoot this problem?

Here is the JavaScript code that I am using:

$(document).ready(function(){
    $("#add_row").click(function(){
        var newCommercial = $("<div class='singleCommercial'><div class='form-group'><input class='datetimepicker'></div>");
        newCommercial.appendTo($('#listOfCommercials'));

        newCommercial.find('.datetimepicker').val(dd+"/"+mm+"/"+yy+" "+time).datetimepicker();
    });

    $("#delete_row").click(function() {
        $(this).closest('.singleCommercial').remove();

    });
});

You can view the full page on my fiddle: http://jsfiddle.net/7yd5o63q/12/

Thank you in advance for your assistance!

Answer №1

closest is utilized to choose the nearest ancestor. The element you are trying to target is not the ancestor of the button.

If you wish to remove the last element, you can opt for the :last selector or utilize last().

You currently have a duplicate id singleCommercial in your HTML code. This is not considered valid HTML; it should be removed. If needed, you can use it as a class instead.

Demo

$(document).ready(function() {
  $("#add_row").click(function() {
    var newCommercial = $("<div class='singleCommercial'><div class='form-group'><input class='datetimepicker'></div>");
    newCommercial.appendTo($('#listOfCommercials'));

    // newCommercial.find('.datetimepicker').val(dd + "/" + mm + "/" + yy + " " + time).datetimepicker();
  });

  $("#delete_row").click(function() {
    $('.singleCommercial:last').remove();
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="listOfCommercials">
  <div id="singleCommercial">
    <div class="form-group">
      <input type='text' class="form-control datetimepicker" id='datetimepicker' name="appearanceDate0" />
    </div>
  </div>
</div>
<button id="add_row" class="btn btn-default">Add Row</button>
<button id="delete_row" class="btn btn-default">Delete Row</button>

Answer №2

If you're looking to eliminate the final .singleCommercial element from the list where you are adding div, here's how you can do it:

Try this:

$("#delete_row").click(function() {
    $('#listOfCommercials > .singleCommercial').last().remove();
});

The use of the .closest() function in jQuery is important as it helps select the parent ancestor of the current element. In this case, the element #delete_row indicated by your this variable cannot locate the .singleCommercial using .closest() since it is not a direct parent and is situated in a different hierarchy. Therefore, an empty set of jQuery objects is returned, resulting in nothing being removed.

To address this, you can either delete the last element within the #listOfCommercials section. Alternatively, you could insert a delete button inside the .singleCommercial and then utilize .closest() to remove the entire block.

An Updated Demo Fiddle showcasing removal of solely the final element within the #listOfCommercials div block

http://jsfiddle.net/zmL7j3xL/1/

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

Executing two AJAX requests simultaneously with Django, AJAX, and jQuery in a single event

I believe I'm on the right track to getting this to work, but I could really use some assistance with the JQuery aspect. It seems that everything functions as expected after the second click onwards, but there is an issue with the functionality on the ...

Is there a way to modify the state following a sorting operation?

How can I properly update the state after sorting by salary? state = { workers: [ {name: 'Bob', surname: 'Meljanski', salary: 5140}, {name: 'Michel', surname: 'Hensson', salary: 5420}, {n ...

Difficulty navigating through pages on an iPad due to slow scrolling with JavaScript

My operation is executed within a scroll function, like this: Query(window).scroll(function(){ jQuery('.ScrollToTop').show(); // my operation. }); While my web page responds quickly to the operation, it seems slo ...

Struggling with identifying jQuery ajax errors?

I am attempting to handle all errors on my own. When an error occurs in jQuery.ajax(), I can detect it using the error options. However, this error is not catchable by my window.onerror event. window.onerror = function(e) { console.log("I was here! E ...

Error in electron-builder: Module 'dmg-license' was not found

Seeking a straightforward method to create an electron app for macOS from a Linux machine. Unfortunately, the electron-builder -m command is not functioning properly. Here is the complete output of the command: electron-builder -m • elec ...

several javascript onclick event listeners for manipulating the DOM

I am currently experimenting with d3 and attempting to create a simple webpage to showcase my d3 examples for future reference. The page displays the output of the d3 code (specifically, the force layout from Mike Bostock) and then embeds the correspondin ...

Is it possible to utilize Nuxt context within nuxt.config.js?

I am utilizing nuxt-i18n and @nuxtjs/auth in my project. I am looking to configure the auth.redirect option to support i18n as shown below: // nuxt.config.js export default { modules: [ '@nuxtjs/auth', 'nuxt-i18n', // .. ...

Is there a way to tally ng-required errors specifically for sets of radio buttons?

Currently, I am working on a form in AngularJS that includes groups of radio buttons. One of my goals is to provide users with an error count for the form. However, I have encountered a peculiar issue: After implementing this code to keep track of errors ...

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

What is the best way to correctly render several React components using a single index.js file?

I am facing an issue with rendering two React component classes. One class creates a counter and works fine, while the other class generates a simple string wrapped in HTML tags but does not render. I have tried various tutorials to troubleshoot this probl ...

Exploring Event Propagation in AngularJS

Currently, I am working on developing a web application using angularjs for the first time. A key feature that I aim to introduce is the ability for users to create a div in the main window upon clicking on an image in the menu. To achieve this functional ...

What could be causing the delay in this script's execution?

I'm attempting to include a script at the beginning of my XBL file, however even the test below is not functioning. Any insight on why this might be happening? <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/x ...

Creating an Engaging Data Visualization: Blending Candlestick Insights with Line Graphs

I'm attempting to display a moving average on a candlestick chart, but I'm facing an issue where the path of the line is not fully appearing on the SVG canvas that I've created. I've searched through various posts to understand how to o ...

What is the best method for choosing elements when I already possess a DOM element?

When you have a variable that contains a DOM element and need to select related elements, you can easily achieve this by wrapping it in a jQuery object. var myDomElement = document.getElementById("foo"); $(myDomElement ).find("a"); It is common for peopl ...

Saving similar and dissimilar information in a database

I have been working on implementing a Like and Unlike feature for users to interact with products. Following this tutorial at , I've completed the necessary steps. However, I'm facing an issue where the likes are not being stored in the database ...

Is it possible to utilize getInitialProps in both _app.js and in individual pages within the application?

I am currently developing my first significant NextJS application. Instead of hardcoding the left navigation data directly into the app, I have set it up to pull in JSON data. This allows me to make minor changes to the site's navigation without havin ...

Aligning text to the center and having it displayed on either side of it

Hey there, I need help with the following: <div id='1'></div> <div id='2'></div> <div id='3'></div> I want to place a single word into each div. The width of each div should be ...

The surprising twist of hasOwnProperty's behavior

I am currently working on a function that is designed to check whether an object contains keys such as 'id' or 'serif:id'. However, I have encountered some issues with its functionality. function returnIdPreferSerifId(object) { if ...

Discovering the best way to organize and sort information retrieved from the backend within an Angular

How can I restrict a user to only search for data that has been provided from the backend and prevent them from creating new data? In my backend, there are two words: "Chart" and "Map". I am looking for a way to limit the user's search to only these ...

Discovered an issue with AngularJS involving ng-show and ng-if?

Upon my investigation, I have identified multiple issues with angularjs: <div ng-show="['[]']">this should be displayed but it is not working as expected</div> <div ng-show="[]">this should be displayed but it is not working as ...