Getting ID of all elements of a certain class into an array

后端 未结 3 705
南笙
南笙 2021-01-12 07:45

Here\'s what I\'m trying to do:

Currently I am using this to create an array of all elements matching the class name of .cookie. Right now I am getting

相关标签:
3条回答
  • 2021-01-12 08:00
    var cookiesArray = new Array();
    $('.cookie').each(function() { 
      var id = $(this).attr(id);
      if(id != undefined) {
        cookiesArray.push(id);
      }
    });
    
    0 讨论(0)
  • 2021-01-12 08:19

    I think this should do what you're after:

    var ids = $('.cookie').map(function(index) {
        // this callback function will be called once for each matching element
        return this.id; 
    });
    

    Documentation for map.

    Here's a working jsFiddle demo.

    0 讨论(0)
  • 2021-01-12 08:21

    You can try:

    var cookiesArray = [];
    
    $('.cookie').each( function(i,e) {
        /* you can use e.id instead of $(e).attr('id') */
        cookiesArray.push($(e).attr('id'));
    });
    
    0 讨论(0)
提交回复
热议问题