Reputation: 63727
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
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
Reputation: 73966
try this,
$.each( $('#collection').children(), function(index, child) {
$('#result').append( child.data('title') );
});
Upvotes: 0
Reputation: 148180
First argument if each() is index
, use second.
$.each( $('#collection').children(), function(index, child) {
$('#result').append( $(child).data('title') );
});
Upvotes: 1
Reputation: 6666
This will work.
$('#result2').html( $('#collection #1').data('title') );
$.each( $('#collection').children(), function() {
$('#result').append( $(this).data('title') );
});
Upvotes: 3
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