Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store data in array within a loop jQuery

How do I store data in array within a loop?

    var images;
    var i = 0;

    $('#cover div').each(function()
    {
        alert($(this).attr('id'));
        //I should store id in an array
    });


    <div id="cover">
        <div id="slider_1"><p class="content">SLIDER ONE</p></div>
        <div id="slider_2"><p class="content">SLIDER TWO</p></div>
        <div id="slider_3"><p class="content">SLIDER THREE</p></div>
    </div>
like image 577
BentCoder Avatar asked Aug 02 '12 13:08

BentCoder


2 Answers

Try this,

var arr = [];
i = 0;
$('#cover div').each(function()
{
        alert($(this).attr('id'));
        arr[i++] = $(this).attr('id');
        //I should store id in an array
});

other Way for getting id using javascript object instead of jquery for increasing performance.

var arr = [];
i = 0;
$('#cover div').each(function()
{
      arr[i++] = this.id;
});

Edit You can also use jQuery map()

Live Demo

arr = $('#cover div').map(function(){
    return this.id;
});
like image 117
Adil Avatar answered Sep 22 '22 09:09

Adil


javascript Arrays have a method push(el) like this:

var images;
var i = 0;

$('#cover div').each(function()
{
    alert($(this).attr('id'));
    images.push($(this).attr('id'));
});

<div id="cover">
    <div id="slider_1"><p class="content">SLIDER ONE</p></div>
    <div id="slider_2"><p class="content">SLIDER TWO</p></div>
    <div id="slider_3"><p class="content">SLIDER THREE</p></div>
</div>
like image 44
Jaro Avatar answered Sep 21 '22 09:09

Jaro