获取子ID列表

时间:2013-12-21 19:03:08

标签: javascript jquery html

Helllo,我有一个具有以下结构的div:

<div id = 'outside'>
    <div id = 'inside1'>
        <img id = 'image1' src='some.png'>
    </div>
    <div id = 'inside2'>
        <img id = 'image2' src='some2.png'>
    </div>
    ...
</div

外部div的内容是从预加载的元素自动生成的,我想将它的结构转换为php。传递整个html()内容非常繁重。

如何使用js或Jquery只保存变量中子div和图像的id?

4 个答案:

答案 0 :(得分:1)

您可以使用.find('*')获取源元素中的所有descendants,然后使用.each遍历所有这些元素,相应地获取元素id并存储在array

尝试,

var xIds = [];

$('#outside').find('*').each(function(){
   xIds.push($(this).attr('id'));
})

DEMO

答案 1 :(得分:1)

您可以使用$ .map

var arr = $.map($('#outside').children(), function(el) {
    var o = {};
    o[el.id] = $.map($('img', el), function(el2) {return el2.id;});
    return o;
});

// returns an array of objects where the parents are keys
// and the values are arrays of the images inside
// [
//   {
//     "inside1": [
//       "image1"
//     ]
//   },
//   {
//     "inside2": [
//       "image2"
//     ]
//   }
// ]

FIDDLE

答案 2 :(得分:1)

获取所有id s:

var allIds = $('#outside').find('[id]').map(function(){ return this.id; }).get();

JS Fiddle demo

参考文献:

答案 3 :(得分:1)

这是一个纯JS方法,用于将“outside”div的所有子节点的ID放入“childrenIDs”数组中:

var children = document.getElementById('outside').children;
var childrenIDs = [];
for (var i = 0; i < children.length; i++) {
    childrenIDs.push(children[i].id);
}
相关问题