user2720132
user2720132

Reputation: 109

Create an array from id's from divs

On my page I've got many div elements which have the same class:

<div class="item" id="lorem">Asdf</div>
<div class="item" id="ipsum">Asdf</div>
<div class="item" id="dolor">Asdf</div>

Now I would like to save the id from every div to an array. It should then look like this:

$array = ["lorem", "ipsum", "dolor"];

How can I do this properly?

Upvotes: 0

Views: 9147

Answers (4)

Tharif
Tharif

Reputation: 13971

Here item is your class name

var x = $('.item').map(function () {
    return this.id;
}).get();
console.log(x);

jQuery.map() function

Upvotes: 0

sunil chugh
sunil chugh

Reputation: 9

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="/jquery/jquery-2.1.3.min.js"></script>
    </head>
    <body>
        <div class="item" id="lorem">Asdf</div>
        <div class="item" id="ipsum">Asdf</div>
        <div class="item" id="dolor">Asdf</div>
        <script>
            $(document).ready(function(){
                var res = Array();
                $('.item').each(function(index,`obj`){
                   res.push(obj.id);
                });
                console.log(res);
            });
        </script>
    </body>
</html>

Upvotes: 0

111
111

Reputation: 1779

You can get id of div in array many ways

var IDs = [];
$(".item").each(function(){ IDs.push(this.id); });
console.log(IDs);

or

var ids = $('.item').map(function(index) {
    return this.id; 
});
console.log(ids);

Upvotes: 0

darkknight
darkknight

Reputation: 372

You can use the each() function of jQuery and iterate over each div to get the id and push it into an array.

var $array = [];
$('div').each(function(){
    var id = $(this).attr('id');
    $array.push(id);
});

Here is a jsFiddle: http://jsfiddle.net/3mokjL6b/2/

Upvotes: 3

Related Questions