0

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?

4 Answers 4

3

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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);

1 Comment

first one is array and second is object
0
<!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>

Comments

0

Here item is your class name

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

jQuery.map() function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.