如何在JQuery中从Parent Div ID获取子div的ID,类和名称?

时间:2015-08-05 14:10:00

标签: jquery html

如何获得儿童div的ID" ClonablePart class"在以下HTML?

<div id="Finance_panel" class="panel>
 <div id="Finance_panel1" class="panel clonablePart"></div>
 <div id="Finance_panel2" class="panel clonablePart"></div>
 <div id="Finance_panel3" class="panel clonablePart"></div>
</div>

演示小提琴:https://jsfiddle.net/tL9spngx/1/

3 个答案:

答案 0 :(得分:1)

您可以使用.map()函数获取其中返回属性的对象以及.get()以转换为数组:

$('#Finance_panel .clonablePart').map(function(){
  return this.id;
}).get();

<强> Working Demo

答案 1 :(得分:1)

首先,你应该修复HTML,因为它有一个可能导致错误的拼写错误;在第一个div的类值的末尾添加双引号。

要获取目标元素的id,首先选择目标元素。然后,循环遍历元素以执行您想要对id执行的任何操作,例如,console.log它们,更改它们,将它们添加到数组中,连接它们等等。

所以,使用这个HTML(错字修复):

<div id="Finance_panel" class="panel">
    <div id="Finance_panel1" class="panel clonablePart"></div>
    <div id="Finance_panel2" class="panel clonablePart"></div>
    <div id="Finance_panel3" class="panel clonablePart"></div>
</div>

您可以使用此JS获取所需的ID:

$("#Finance_panel").find(".clonablePart").each(function () {
    var id = this.id;

    // Replace the console.log statement below with whatever operation you want to perform with the id
    console.log("The id of this div is " + id);
});

JSFiddle

答案 2 :(得分:0)

jquery的用户attr属性获取任何HTML标记属性

var lengthPanel = $("#Finance_panel").find('.clonablePart');
var class = lengthPanel.attr('class');
var id = lengthPanel.attr('id');
var style = lengthPanel.attr('style');
相关问题