Creating an array of objects by capturing a data attribute

I made a violin. http://jsfiddle.net/Zfaf6/

I'm experimenting with arrays, but only seems to output the first object.

Can anyone please advise, thanks.

My jquery

$("a.download-all").on('click', function () {

    var downloads = $('a[data-download]').attr('data-download');

    // This is the example output of the data in the variable...

    $('#varObj').html(downloads);

});

      


My script

<div id="images">

    <a href="#" data-download="http://image.com/1.jpg"><img src="images/x.gif" alt=""/></a>
    <a href="#" data-download="http://image.com/2.jpg"><img src="images/x.gif" alt="" /></a>
    <a href="#" data-download="http://image.com/3.jpg"><img src="images/x.gif" alt=""/></a>
    <a href="#" data-download="http://image.com/4.jpg"><img src="images/x.gif" alt="" /></a>
    <a href="#" data-download="http://image.com/5.jpg"><img src="images/x.gif" alt=""/></a>
    <a href="#" data-download="http://image.com/6.jpg"><img src="images/x.gif" alt="" /></a>

<div>

<p><a href="#" class="download-all">Download all images</a></p>

<p id="varObj"></p>

      

http://jsfiddle.net/Zfaf6/

+3


source to share


4 answers


jQuery attr()

will be the "getter" ( and in docs ) will return the value of the first matched element; so you only see one.

Iterate over matching objects with each()

or use map()

;



$("a.download-all").on('click', function () {

    var downloads = $('a[data-download]').map(function () {
        return $(this).attr('data-download');
    });

    // This is the example output of the data in the variable...
    $('#varObj').html(downloads.get().join(' '));
});

      

+5


source


LIVE DEMO



var downloads = [] ;

$("a.download-all").on('click', function () {

    $('a[data-download]').each(function(){   
        downloads.push( $(this).attr('data-download') );        
    });

    $('#varObj').html(downloads);

});

      

+1


source


calling the attr () set will only return the first attr (). Also, use data()

as it is easier to read.

So the code just creates an empty array, and then using each

, we push each element download

into the array. The rest of your code is the same.

$("a.download-all").on('click', function () 
{
    var downloads = [];

    $('a[data-download]').each(function()
    {
        downloads.push( $(this).data('download') );
    });

    // This is the example output of the data in the variable...

    $('#varObj').html(downloads);
});

      

+1


source


var downloads = $('a[data-download]').map(function(){   
   return  $(this).data('download');        
});
$("#varObj").html(downloads.join("-"));

      

+1


source







All Articles