how to select all children elements and their attributes in jQuery [duplicate]

Solution 1:

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"

Solution 2:

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.

Solution 3:

Simple solution (ES6)

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

Online demo (jsFiddle)