Guide on how to retrieve the parent element's number when dragging starts

Within my div-containers, I have a collection of div-elements. I am looking to identify the parent number of the div-element that is currently being dragged

For example, if Skyler White is being dragged, the expected output should be "0" as it is from the first subcontainer with the id "subcontainer". If Jesse Pinkman is being dragged, the output should be 1

<div id="container">
<div id="subcontainer">
<div id="0" draggable="true">Walter White</div>
<div id="1" draggable="true">Skyler White</div>
<div id="2" draggable="true">Hank Schrader</div>
</div>
<div id="subcontainer"></div>
<div id="0" draggable="true">Saul Goodman</div>
<div id="1" draggable="true">Jesse Pinkman</div>
</div>
</div>

Answer №1

  • Utilize the .index() method provided by jQuery
  • Use .closest to target the closest element related to the current element
  • Implement the drag event to select the specific current element

It is important to keep in mind that there should not be multiple elements with the same id value within a single document.

$('div[draggable]').on('drag', function() {
  $('#output').text('Parent Index is: ' + $(this).closest('.subcontainer').index());
});
#output {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
  <div class="subcontainer">
    <div id="0" draggable="true">Walter White</div>
    <div id="1" draggable="true">Skyler White</div>
    <div id="2" draggable="true">Hank Schrader</div>
  </div>
  <div class="subcontainer">
    <div id="0" draggable="true">Saul Goodman</div>
    <div id="1" draggable="true">Jesse Pinkman</div>
  </div>
</div>
<br/>
<br/>
<div id="output"></div>


JavaScript only approach:

  • Iterate through the NodeList returned by Document.querySelectorAll() using [].forEach.call
  • Attach an eventListener to each matched element utilizing addEventListener
  • Convert the NodeList using [].slice.call so we can use the indexOf method of Array
  • this.parentElement will retrieve the parent element of the current element

[].forEach.call(document.querySelectorAll('div[draggable]'), function(elem) {
  elem.addEventListener('drag', function() {
    var elemsArray = [].slice.call(document.querySelectorAll('.subcontainer'));
    var index = elemsArray.indexOf(this.parentElement);
    document.getElementById('output').textContent = 'Parent Index is: ' + index;
  });
});
* {
  padding: 0;
  margin: 0;
}
#output {
  font-weight: bold;
}
<div id="container">
  <div class="subcontainer">
    <div id="0" draggable="true">Walter White</div>
    <div id="1" draggable="true">Skyler White</div>
    <div id="2" draggable="true">Hank Schrader</div>
  </div>
  <div class="subcontainer">
    <div id="0" draggable="true">Saul Goodman</div>
    <div id="1" draggable="true">Jesse Pinkman</div>
  </div>
</div>
<br/>
<br/>
<div id="output"></div>

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

It appears that the functionality of RegExp.prototype.exec() is not functioning as expected

const fs = require('fs') const jsdocFinder = /\/\*\*\n(.+?)\*\//gs /** * Implementing a function to convert JSDocs into JSON format. * @function * @param {String[] | String} dirs The directory or directories of ...

The controller's AngularJS function seems to be unresponsive

Issue with AngularJs ng-click Event I'm attempting to utilize the GitHub Search-API. When a user clicks the button, my Controller should trigger a search query on GitHub. Here is my code: HTML: <head> <script src="js/AngularJS/angula ...

Determine the data type of a property within a JavaScript object

I am currently working with a javascript object that looks like this: venue = { id: 0, name: '', venueimage_set: [ { imageurl: '', }, ]... At a later point in my code, I need to modify the object ...

Submit data via POST method on the modified URL

I need assistance with modifying the data of a URL and making a POST request to it. The URL in question is as follows: http://domanin.com/search-result/?start=06%2F08%2F2017&end=06%2F09%2F2017&room_num_search=1&adult_number=1&children_num= ...

Understanding the significance of underscores in JavaScript strings

Some places mention using _() around strings like _('some string'). For instance, in a desktop program with these imports: const Applet = imports.ui.applet; const St = imports.gi.St; const Gdk = imports.gi.Gdk; const Gtk = imports.gi.Gtk; const ...

Exploring paths deep within by employing wildcards as a query

I have data structured according to Firebase's flat structure advice, storing quotes in nodes like this: quotes -> clientName -> quoteObject Each 'quoteObject' includes a 'dateCreated' value that I aim to retrieve as follow ...

The information retrieved from an API fails to populate the table on the NextJS platform

I am facing an issue while trying to populate a table using an API call in NextJS. I have used the getStaticProps function to retrieve the data and pass it to the component. However, when I attempted to use the map() function to iterate over the data objec ...

Load suggestions from Material UI AutoComplete dynamically based on user input

I am facing a challenge with an Autocomplete component that needs to handle a large data list, up to 6000 elements, and display suggestions based on user input. Due to the sheer number of options, when a user types on a slower computer, there is a noticeab ...

Execute a series of Promises (or Deferreds) consecutively and have the flexibility to pause or stop at any point

Having an issue here. Need to make numerous consecutive http calls and the ability to stop the process at any point in time. The current solution I have involves jQuery and Deferreds, but it lacks proper interruption handling (still haven't transition ...

Including v-menu in a button causes it to vanish in Vuetify

I am facing an issue with my stepper. Specifically, in step 3, I am trying to add a v-menu to a button but when I do so, the button disappears. Below is the code snippet causing the problem: <template> . . . . <v-stepper-step :complete="e6 > ...

The Axios POST request successfully sends the data to the Express server but unfortunately encounters a 404 error

Error 404 when Sending Data from Axios POST Request to Express Server Hey there! I'm currently working on setting up a user authentication server for a project, but I've hit a roadblock while attempting to send a POST request to my Node.js Expre ...

The AJAX response containing jQuery is failing to produce any visible changes

On Page 1 of my website, there is a form that, upon submission, loads Page 2 using jQuery. This process involves calling a PHP page and displaying the output on Page 1 without actually reloading the entire page. To maintain security, I have set up session ...

Exploring the World of Html

I'm struggling with an HTML problem related to a web programming class I'm taking. The assignment involves creating a video game using HTML and JavaScript, where an image moves randomly on the screen and the player must click on it as many times ...

Implement lazy loading of content on scroll in Grails framework

Currently, I am uploading images and displaying them in a gsp view. My goal now is to implement a functionality where the images load as I scroll down on the page. A friend suggested using jQuery to make an ajax call for this. Can someone please provide g ...

Tips for choosing a specific cell in a table

I currently have a total of 14 cells that have been generated. Is there a way for me to individually select and manipulate a specific cell out of the 14? I am looking to make only one cell unique, while leaving the rest to be displayed as they are in the ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

The challenge of mapping React Select

I have implemented react-select in my project and I am using it within a map function like this: renderItems() { this.props.items.map(item => ( <Select id="options" value={this.state.optionSelected} onChange={this.onChangeOpt ...

Arranging numerous Text elements within a solitary Drag and Drop container with the z-index property

I am facing a challenge with stacking twelve arguments in no particular order on a drag and drop element. The texts overlap each other, making it difficult for the end user to see them clearly when dragging and dropping. Is there a way to stack texts using ...

Allow for the ability to choose a specific option for every individual line that is echoed in

I have researched several similar questions, but none of them address exactly what I am attempting to achieve. My goal is to use AJAX to fetch a PHP page that will display the contents of a folder on my server. Currently, the files are being listed line by ...

retrieving a promise fails during the set interval

Hey there! I'm currently a computer science student and still getting the hang of things. Recently, I encountered an issue that I can't seem to solve on my own. The problem is related to fetching data from my MongoDB database every few seconds an ...