The page has the nth number of elements with the same class and the data-id attribute. How to get the data-id values ​​of all the elements with a given class?

<span class="select" data-id="1">one</span> <span class="select" data-id="2">two</span> <span class="select" data-id="3">three</span>... 

    2 answers 2

    To convert one collection to another and in the usual javascript there is a map method and in jQuery there is a map method

    These methods allow you to get a collection of attribute values, for example

     //jQuery console.log($('.select[data-id]').map(function() { return this.dataset.id; }).get()); //vanilla console.log([].map.call(document.querySelectorAll('.select[data-id]'), function(el) { return el.dataset.id; })); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="select" data-id="1">one</span> <span class="select" data-id="2">two</span> <span class="select" data-id="3">three</span> <span class="select" data-id="4">one</span> <span class="select" data-id="5">two</span> <span class="select" data-id="6">three</span> 

      For example:

       $('[data-id]').each( function(e){ var $el = $(this); if($el.hasClass('test')) { console.log($el.attr('data-id')) } }) 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="test" data-id="1"></li> <li data-id="2"></li> <li class="test" data-id="3"></li> <li data-id="4"></li> <li class="test" data-id="5"></li> </ul>