Nyxynyx
Nyxynyx

Reputation: 63727

Using $.each() to get data attributes

When I used $('#1').data('title') to extract the attribute data-title, it works.

Problem: When I try to extract all the data-title attributes from the elements that are the children of div #collection using $.each(), I get the error Uncaught TypeError: Object 0 has no method 'data'. What should be the proper way to do this?

JS Code

$.each( $('#collection').children(), function(index, child) {
    $('#result').append( child.data('title') );
});

jsfiddle: http://jsfiddle.net/J5Fjf/2/

Upvotes: 0

Views: 179

Answers (5)

Jai
Jai

Reputation: 74738

I think you have to catch the index of the divs inside #collection and instead of $.each you can use .each to iterate through:

$('#collection div').each(function(i) {
    $('#result ul').append('<li>' + $('#a'+parseFloat(i+1)).data('title')+'</li>');
});

chekout the fiddle: http://jsfiddle.net/J5Fjf/4/

Upvotes: 0

palaѕн
palaѕн

Reputation: 73966

try this,

$.each( $('#collection').children(), function(index, child) {
  $('#result').append( child.data('title') );
});

Upvotes: 0

Adil
Adil

Reputation: 148180

First argument if each() is index, use second.

$.each( $('#collection').children(), function(index, child) {
    $('#result').append( $(child).data('title') );
});

Upvotes: 1

johan
johan

Reputation: 6666

This will work.

$('#result2').html( $('#collection #1').data('title') );

$.each( $('#collection').children(), function() {
    $('#result').append( $(this).data('title') );
});

Upvotes: 3

adeneo
adeneo

Reputation: 318362

$('#collection').children().each( function(index, child) {
    $('#result').append( $(child).data('title') );
});

The second argument in each() would be the native DOM element, while the first argument is the index of the loop. When iterating a jQuery set of elements, you can also use each as a chained function, and this would also referrence the element inside the loop.

Upvotes: 2

Related Questions