Javascript 如何遍历div的子div并获取子div的id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11291300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to loop over the child divs of a div and get the ids of the child divs?
提问by Ahmad
I have a div with id test
我有一个带有 id 测试的 div
and through the foreach loop I am creating some inner divs inside the test div. So it becomes like this.
通过 foreach 循环,我在测试 div 中创建了一些内部 div。所以就变成这个样子了。
<div id="test">
<div id="test-1"></div>
<div id="test-2"></div>
<div id="test-3"></div>
<div id="test-4"></div>
</div>
I am getting the parent div id "test" in the javascript function. Now I want to loop through the inner divs(child divs) of the test div and get the id of the each div one by one and style them through javascript.
我在 javascript 函数中获取父 div id“test”。现在我想遍历测试 div 的内部 div(子 div)并一一获取每个 div 的 id 并通过 javascript 设置它们的样式。
Any Idea about this?
有什么想法吗?
采纳答案by aaberg
You can loop through inner divs using jQuery .each() function. The following example does this, and for each inner div, it gets the id attribute.
您可以使用 jQuery .each() 函数遍历内部 div。下面的示例执行此操作,并且对于每个内部 div,它获取 id 属性。
$('#test').find('div').each(function(){
var innerDivId = $(this).attr('id');
});
回答by yogi
Try this
尝试这个
var childDivs = document.getElementById('test').getElementsByTagName('div');
for( i=0; i< childDivs.length; i++ )
{
var childDiv = childDivs[i];
}
回答by lesandru
Here's the solution if somebody still looks for it
如果有人仍在寻找它,这是解决方案
function getDivChildren(containerId, elementsId) {
var div = document.getElementById(containerId),
subDiv = div.getElementsByTagName('div'),
myArray = [];
for(var i = 0; i < subDiv.length; i++) {
var elem = subDiv[i];
if(elem.id.indexOf(elementsId) === 0) {
myArray.push(elem.id);
}
}
return myArray;
}
console.log(getDivChildren('test', 'test-'));
回答by Shikiryu
回答by nbrooks
What you are trying to do is loop through the direct-descendant divs of the #test
div; you would do this using the >
descendant selector, and the jQuery .each()
iterator. You can also use the jQuery .css()
and .attr()
methods for styling and retrieving the id respectively.
您要做的是循环遍历 div 的直接后代#test
div;您可以使用>
后代选择器和 jQuery.each()
迭代器来完成此操作。您还可以分别使用 jQuery.css()
和.attr()
方法来设置样式和检索 id。
$("#test > div").each(function(index){
var id = $(this).attr("id");
$(this).css(/* apply styles */);
});
回答by Hooch
Use jQuery.
使用 jQuery。
This code can be addapted to your needs:
可以根据您的需要添加此代码:
$testDiv = ?$('div#test')????????????.first();
$('div', $testDiv).css("margin", '50px');????