Javascript JQuery:如何遍历 div 的所有子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11874799/
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
JQuery: How to loop through all child elements of a div
提问by some_bloody_fool
I am trying to loop through all elements in a given div and output the results (C# code i will use later) to the screen for testing.
我正在尝试遍历给定 div 中的所有元素并将结果(我稍后将使用的 C# 代码)输出到屏幕进行测试。
so if i have html like this:
所以如果我有这样的 html:
<div id="testDiv">
<test>
<a>aVal</a>
<c>
<cc>ccVal</cc>
</c>
</test>
</div>
i am trying to produce this string value:
我正在尝试生成此字符串值:
HtmlElement.CreateNode("test").AddNode(CreateNode("a").addText("aVal")).AddNode(CreateNode("c").AddNode(CreateNode("cc").addText("ccVal"))
Right now i ahve this jquery in place, but i am unsure of how to drill down into the other nodes:
现在我已经有了这个 jquery,但我不确定如何深入到其他节点:
var x = "HtmlElement.";
$('div#testDiv').children().each(function () {
var nodeNameStr = this.nodeName.toLowerCase();
var nodeText = $(this).text();
x += "CreateNode(nodeNameStr).addText(nodeText)"
});
采纳答案by driangle
Here's a more complete example than previous answers:
这是一个比以前的答案更完整的示例:
// returns the 'AddNode(...)' method call for every child.
function addChildren(element){
var command = "";
$(element).find("> *").each(function(){
command += ".AddNode("+createNode(this)+")";
});
return command;
}
// if the element has text, add the text
function addText(element){
var elementText = $(element).clone().children().remove().end().text().trim();
if(elementText) {
return ".addText(\""+elementText+"\")";
} else {
return "";
}
}
// returns the 'CreateNode(...)' method call for a node and all its children.
function createNode(element){
var nodeName = element.nodeName.toLowerCase();
var csharpCommand = "CreateNode(\""+nodeName+"\")";
csharpCommand += addChildren(element);
csharpCommand += addText(element);
return csharpCommand;
}
// begin
$("div#testDiv > *").each(function(){
var csharpCommand = "HtmlElement."+createNode(this);
console.log(csharpCommand);
});
回答by Gabe
回答by JCOC611
You are looping through the direct children of your div, rather than all the children. To do so, use this code:
您正在遍历 div 的直接子级,而不是所有子级。为此,请使用以下代码:
$('div#testDiv *').each(function(){
// Your Code
});
回答by befree2j
You can use the div id to get all the children in the following way:
您可以使用 div id 通过以下方式获取所有子项:
$('#youDivId').children().each(function(){
alert(this.value);
});