admin管理员组文章数量:1418140
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
本文标签: javascriptCreate an array from id39s from divsStack Overflow
版权声明:本文标题:javascript - Create an array from id's from divs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745267896a2650713.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论