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

前端 未结 3 886
温柔的废话
温柔的废话 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: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:

  • and (see jQuery data()):

    $('li.tab_item').data("foo"); // -> "some custom data"
    

提交回复
热议问题