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?
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?
Share Improve this question edited Mar 18, 2015 at 7:50 Suhaib Janjua 3,57216 gold badges69 silver badges87 bronze badges asked Mar 18, 2015 at 7:23 user2720132user2720132 1092 silver badges7 bronze badges4 Answers
Reset to default 3You 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/3mokjL6b/2/
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);
<!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>
Here item is your class name
var x = $('.item').map(function () {
return this.id;
}).get();
console.log(x);
jQuery.map() function