Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map an element's children to their data attribute values?

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'))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading