user753531
user753531

Reputation:

How to get a Node position in a NodeList?

TL;DR

How can I retrieve a Node position in a NodeList? Position in the meaning of offset in a zero-based structure, not position as top or left


I have a jQuery UI Draggable/Droppable that fills an Array when a dragged element is dropped. Because it's very simple I use a simple Array.push()

When building the UI to show something about the dragged element (a thumbnail for what matters), I retrieve this Array and manipulate the last Node previously created. Regardless of all other possibilities to get the last Node, I'm retrieving it by offset, when it's equal to the number of elements I have already registered:

let offset  = mySource.length;

// Sounds like a bathroom >.<

let $item = $( '#data .entry' ).eq( offset ).addClass( 'occupied' );

It works, but these elements can, eventually, be removed so the Array must obviously be updated. But to do so I need an offset for, maybe, Array.slice(), and I was thinking about (and here comes the question) getting the position of the parent of the clicked element (that triggered the removal action) and use it as offset, since both Array and NodeList are, one way or another, zero-based collections.

Considering a NodeList structure like this:

.fa {
  cursor: pointer;
  margin-left: 5px;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div id="data">

  <div class="entry">
    <p>
      Lorem ipsum dolor blah blah blah #1
      <span class="fa fa-trash" title="Remove"></span>
    </p>
  </div>
  
  <div class="entry">
    <p>
      Lorem ipsum dolor blah blah blah #2
      <span class="fa fa-trash" title="Remove"></span>
    </p>
  </div>
  
  <div class="entry">
    <p>
      Lorem ipsum dolor blah blah blah #3
      <span class="fa fa-trash" title="Remove"></span>
    </p>
  </div>
  
  <div class="entry">
    <p>
      Lorem ipsum dolor blah blah blah #4
      <span class="fa fa-trash" title="Remove"></span>
    </p>
  </div>
  
  <div class="entry">
    <p>
      Lorem ipsum dolor blah blah blah #5
      <span class="fa fa-trash" title="Remove"></span>
    </p>
  </div>
  
</div>

How could I get the position of the Node .entry inside the #data when its child .fa is clicked?

Upvotes: 0

Views: 947

Answers (1)

charlietfl
charlietfl

Reputation: 171669

How could I get the position of the Node .entry inside the #data when its child .fa is clicked?

Use closest() to traverse up to the parent entry and get it's index()

$('#data .entry .fa').click(function(){
   // target entry instance
   var $entry = $(this).closest('.entry');
   // get entry instance index amongst it's siblings
   var entryIndex = $entry.index();    
});

Upvotes: 0

Related Questions