How to get an array of attribute value from elements in a jQuery object

前端 未结 3 887
温柔的废话
温柔的废话 2021-01-12 02:04

I use a custom attribute in elements with my own class. I\'m trying to return the value of custom attribute for all elements of the class.

I used jQuery to find th

相关标签:
3条回答
  • 2021-01-12 02:37

    Use .map():

     $("li.tab_item").map(function (){
        return this.getAttribute("myAttribute");
     });
    

    That gives you an Array of values wrapped in a jQuery object. If you want to get the Array, call .get(), ie .map(...).get().

    By the way, you can also select the elements by attribute instead of class:

    $("[myAttribute]")
    

    This will return all elements on the page that have a myAttribute attribute.

    0 讨论(0)
  • 2021-01-12 02:38
    var tab_attribs = $('li.tab_item').map(function () {
      return $(this).attr("custom_attribute");
    });
    

    This will give you an array of the custom attribute values. Of course, you can do this more traditionally:

    var tab_attribs = [];
    $('li.tab_item').each(function () {
      tab_attribs.push( $(this).attr("custom_attribute") );
    });
    

    Anyway, you should probably make use of the data-* attributes that HTML5 provides:

    <li class="tab_item" data-foo="some custom data">
    

    and (see jQuery data()):

    $('li.tab_item').data("foo"); // -> "some custom data"
    
    0 讨论(0)
  • 2021-01-12 02:38

    Simple solution (ES6)

    Array.from(document.getElementsByClassName('tab_item')).map(item => item.getAttribute('foo'));
    

    Online demo (jsFiddle)

    0 讨论(0)
提交回复
热议问题