Home > front end >  How to map an element's children to their data attribute values?
How to map an element's children to their data attribute values?

Time:12-22

Given a parent element, how can I get a collection with all the data-chartid attribute values?

<div id="chart-container">
  <div data-chartid="1">...</div >
  <div data-chartid="2">...</div >
  <div data-chartid="3">...</div >
</div>

I'm trying to duplicate the syntax used on this page, but it seems to fail on several levels.

$('#chart-container').children().map(c => $(c).data('chartid'))

Note: All top-level children are <div>s so maybe the selector could be modified so children() isn't necessary.

CodePudding user response:

The first parameter passed to the map callback is the index. The second is the item:

const res = $('#chart-container').children().map((index, elem) => $(elem).data('chartid')).toArray()
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart-container">
  <span data-chartid="one"></span>
  <span data-chartid="two"></span>
  <span data-chartid="three"></span>
</div>

If you want to duplicate the syntax:

const res = $('#chart-container').children().toArray().map(e => $(e).data('chartid'))
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart-container">
  <span data-chartid="one"></span>
  <span data-chartid="two"></span>
  <span data-chartid="three"></span>
</div>

  • Related