Kevin Brown
Kevin Brown

Reputation: 12650

jQuery set element li data from array

If I have a list:

<div class="item active ui-sortable">
  <li class="player ui-droppable" data-name="Kev" data-pick-id="534dd2424b65762a89020000">
    Teddy Bridgewater
    <div class="pull-right" id="player-badges">
      <span id="points-holder">
        10
      </span>
      <span class="remove-player player-badge">
        <i class="fa fa-trash-o"></i>
      </span>
    </div>
  </li>
  <li class="player pick-blank ui-droppable" data-name="" data-pick-id="534dd2424b65762a89030000">
    EMPTY
    <div class="pull-right" id="player-badges">
      <span id="points-holder">
        7
      </span>
    </div>
  </li>
  <li class="player ui-droppable" data-name="kevin" data-pick-id="534dd2424b65762a89040000">
    kevin
    <div class="pull-right" id="player-badges">
      <span id="points-holder">
        5
      </span>
      <span class="remove-player player-badge">
        <i class="fa fa-trash-o"></i>
      </span>
    </div>
  </li>
</div>

And I'm making an array of data-pick-id, how would I then rewrite this list based on the array ["534dd2424b65762a89020000", "534dd2424b65762a89030000", "534dd2424b65762a89040000"]?

Context: I'm using jquery-sortable and want to preserve the dom structure of the data-pick-id only. That way I can change all the contents and update to server while retaining the actual dom position by ID.

Again, all I want to do is loop through and write that array to each data-pick-id. Would a loop be the best option?

Upvotes: 1

Views: 281

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173562

A simple .each() would suffice:

var ids = [1, 2, 3];

$('.player').each(function(i) {
    $(this).data('pick-id', ids[i]);
});

You may wish to make the selector more explicit.

Upvotes: 1

Related Questions