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

Get data-id of each element with specific classname as string, not as an object

I have a html list like this:

<div id="list">
   <div class="special" data-id="TZ2"></div>
   <div class="special" data-id="KJ1"></div>
   <div class="" data-id="LLT"></div>
   <div class="" data-id="UV3"></div>
   <div class="special" data-id="JQT"></div>
</div>

I want to get all data-ids of divs with classname special, splitted by a comma, as a string.

var myIDs = $("#list > div").each(function() {
   $(".special", this).data('id');
});

With this way I get the myIDs variable as an object, but I just want the data-ids as a string list, like this:

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

TZ2,KJ1,JQT

I also tried this one, after running the each function:

var myIDsString = myIDs.data('id');

But then I only get the data-id of the first object. What’s my fail?


var myIDs = $("#list > div").each(function() {
   $(".special", this).data('id');
});

var myIDsString = myIDs.data('id');

console.log(myIDsString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="list">
   <div class="special" data-id="TZ2"></div>
   <div class="special" data-id="KJ1"></div>
   <div class="" data-id="LLT"></div>
   <div class="" data-id="UV3"></div>
   <div class="special" data-id="JQT"></div>
</div>

>Solution :

First get all Id into array then convert it into string using toString() function.

let myIDs = [];

$(document).find('.special').each(function() {
  let id = $(this).data('id');
  myIDs.push(id);
})

console.log(myIDs.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="list">
  <div class="special" data-id="TZ2"></div>
  <div class="special" data-id="KJ1"></div>
  <div class="" data-id="LLT"></div>
  <div class="" data-id="UV3"></div>
  <div class="special" data-id="JQT"></div>
</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