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

"Clicking on the dropdown menu will consistently result in it collapsing

When it comes to a DropDown menu, the typical expectation is that when an option is selected, the menu will collapse. However, in my situation, I do not want the dropdown menu to collapse if the user is attempting to log in and clicks on the Username and P ...

The issue with ajax in CodeIgniter is that it keeps displaying a false message, even though the value is present

Trying to validate the existence of a value in the CodeIgniter website's database using AJAX. Below is the code snippet: <input id="username" name="pincode" type="text" class="form-control" placeholder="Enter Pincode"> <input id="prodid" n ...

Tips for validating a string in a URL with Selenium IDE

When I click on a tab on my website, it triggers an AJAX service call where the URL contains parameters related to the data being loaded after the tab is clicked. The data is displayed as horizontal tiles one below the other, with 4 tiles being loaded pe ...

Understanding the error handling in Express.js

Learning about error handling in express is new to me and I have a straightforward piece of code like this - const express = require('express'); const MongoClient = require('mongodb').MongoClient; const app = express(); let url = &a ...

Customizing the placeholder font size in Material UI Autocomplete using ReactJS

Is there a way to change the placeholder font size for Material UI Autocomplete? https://i.stack.imgur.com/x71k2.png <Autocomplete multiple id="tags-outlined" options={top100F ...

How can you proactively rebuild or update a particular page before the scheduled ISR time interval in Next.js?

When using NextJS in production mode with Incremental Static Regeneration, I have set an auto revalidate interval of 604800 seconds (7 days). However, there may be a need to update a specific page before that time limit has passed. Is there a way to rebui ...

What is the best way to search for items using only a portion of a phone number or typing a name in any case (uppercase, lowercase) and still get accurate results?

let contacts = [ { name: 'John', phone: 987654 }, { name: 'Sara', phone: 654321 } ] I am developing a contact manager app with various functions to manage contacts. Add new contac ...

Webpack has issues with loading HTML files

I encountered a 404 not found error while attempting to load the HTML page using webpack. Here are my configurations: Webpack.config.js: const path = require('path'); module.exports= { devServer: { // contentBase static : { ...

Converting a stringified array object to an object using Expressjs

When working with Angular, I am sending stringified data using FormData. Here is an example: this.formData.append('data', JSON.stringify(this.collections)) Now my challenge is converting this string back to an object in my Express backend. The d ...

When using jQuery's POST method, the "done" event is triggered, however, no data is being sent

I've been working on implementing AJAX form submission and wrote a function to handle it when the button is clicked: function putUser() { $('button#putUser').on('click', function() { var user = $('input#user' ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...

The internal cjs loader in node threw an error at line 1078

I'm encountering an error on Windows 10 when running the npm command: node:internal/modules/cjs/loader:1063 throw err; ^ Error: Cannot find module 'D:\mobile-version portfolio\ at Module._resolveFilename (node:internal/modules/cjs/load ...

Problem encountered when transferring JSON data to PHP for file writing

After spending numerous hours researching potential solutions, I still can't seem to fix the issue at hand. Admittedly, I am fairly new to PHP, so it's possible that I am overlooking a small detail. The problem lies in the fact that I have a form ...

Attempting to transform a numerical value into CSS syntax

Currently, I am attempting to loop through several DIV elements, extract a numerical value from each DIV, and then based on that value matching a specific value in the JavaScript code, assign a particular CSS Class back to the original DIV. This is the sn ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...

Retrieve particular JSON information on a single webpage by selecting an element on a separate page

My goal is to fetch specific information from a JSON file and display it on different HTML pages by clicking a button. I will achieve this using jQuery and plain JS. For the first HTML page, I want to show all products from the JSON in an element with id= ...

Utilizing AJAX for sending data to a PHP database and automatically updating the page

Currently, I've implemented a button: <ul> <li><button onclick="display('1')">1</button></li> <li><button onclick="display('2')">2</button></li> <li><butto ...

Can we utilize object properties in this manner?

Hey there! I've been experimenting with the react-bootstrap library recently, trying to get better at using it. While going through the tutorial, I came across some ES6 code that caught my attention. function FieldGroup({ id, label, help, ...props } ...

How can I enable the "edit" function for a button within a list item?

I am currently working on a feature that allows users to edit list rows by clicking a button. However, I am facing an issue where the "edit" button only edits the first row instead of the matched line. This functionality is part of a program I am developi ...

Create a PHP form that includes text and image inputs with the help of AdminLTE and integrates DropZone.js

I have been working with a template from adminLTE and you can check it out at the following link: . At this point, I am trying to upload images first and then use the image names as input text elements in my main form for submission. However, I have encou ...