0

I'm working on a drag n drop simple project. Trying to get the javascript code to get the index of the dragged item. After searching found a similar code in jquery.

var index = $(e.target).index();

I want to get this done in javascript. Any help would be appreciated.

<div class="lists">
   <div class="list">
     <div class="list-item">Item 1</div>
     <div class="list-item">Item 2</div>
     <div class="list-item">Item 3</div>
     <div class="list-item">Item 4</div>
     <div class="list-item">Item 5</div>
   </div>
   <div class="list"></div>
   <div class="list"></div>
 </div>

This is the code im working on

  • jQuery _is_ JavaScript. Do you mean, get this done in vanilla JavaScript (no libraries)? – Amadan Feb 14 '20 at 10:17
  • Does this answer your question? [JavaScript DOM: Find Element Index In Container](https://stackoverflow.com/questions/11761881/javascript-dom-find-element-index-in-container) – Terry Feb 14 '20 at 10:18
  • @Amadan i want the DOM way to do it – lucifer_096 Feb 14 '20 at 10:28
  • 4
    http://youmightnotneedjquery.com/#index – Yoshi Feb 14 '20 at 10:29
  • @Yoshi Good link. Another possibility is to assign numbers to attributes of the elements when they are generated, which results in a larger HTML but faster lookup. – Amadan Feb 14 '20 at 10:33
  • 1
    `Array.prototype.indexOf.call(e.target.parentElement.children, e.target)` – Thomas Feb 14 '20 at 10:33
  • You've pulled this line of code out from the context it lived in, it doesn't mean very much on its own. What you want looks like it would be extremely simple but it would be helpful to actually provide the surrounding code if you want a solution - what @Thomas posted is probably the exact thing you need, but your code still doesn't make a whole lotta sense in isolation – DanCouper Feb 14 '20 at 10:34
  • @lucifer_096 You can check this example https://codepen.io/SitePoint/pen/gbdwjj – Pramod Feb 14 '20 at 10:55

0 Answers0