0

I have this HTML:

    <div class="ac-users ac-appender">
        <div class="chip" data-id="3069243" data-text="">IBM(3069243)
            <i class="material-icons close">close</i>
        </div>
        <div class="chip" data-id="6640418" data-text="">INTC(6640418)
            <i class="material-icons close">close</i>
        </div>
        <div class="chip" data-id="1452690" data-text="">RJF(1452690)
            <i class="material-icons close">close</i>
        </div>
    </div>

I need to select from this and get an array of the data-id. $('.chip') selects the array of chips effectively, but I am not able to extract the values of data-id(s)

With jquery I am using the following but it only brings back the first item:

    $('.chip').attr("data-id");
5
  • how are you getting the data-id? Commented Sep 14, 2016 at 3:03
  • can you paste you jquery code here? Commented Sep 14, 2016 at 3:06
  • $('.chip').attr("data-id"); only brings back the first item Commented Sep 14, 2016 at 3:08
  • $('.chip').data('id') Commented Sep 14, 2016 at 3:09
  • 1
    iterate over it Commented Sep 14, 2016 at 3:11

3 Answers 3

1

var arr = $('.chip').map(function() {

  return $(this).attr('data-id');

}).get();

console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ac-users ac-appender">
  <div class="chip" data-id="3069243" data-text="">IBM(3069243)
    <i class="material-icons close">close</i>
  </div>
  <div class="chip" data-id="6640418" data-text="">INTC(6640418)
    <i class="material-icons close">close</i>
  </div>
  <div class="chip" data-id="1452690" data-text="">RJF(1452690)
    <i class="material-icons close">close</i>
  </div>
</div>

Use .map()

Description: Translate all items in an array or object to new array of items.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thank You
1
var dataIds = $('.chip').map(function(i, chip) {
  return chip.getAttribute('data-id');
});

1 Comment

Awesome. Thank You
1

How about this:

$(".chip").map(function() { return $(this).data('id') } ).get();

It gets all elements of class "chip" then calls a function on each element to get the data-id and creates an array of the format:

[3069243, 6640418, 1452690]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.