Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  99] [ 5]  / answers: 1 / hits: 37295  / 12 Years ago, wed, august 8, 2012, 12:00:00

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.



so if i have html like this:



    <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:



var x = HtmlElement.;
$('div#testDiv').children().each(function () {
var nodeNameStr = this.nodeName.toLowerCase();
var nodeText = $(this).text();
x += CreateNode(nodeNameStr).addText(nodeText)
});

More From » jquery

 Answers
24

Here's a more complete example than previous answers:



http://jsfiddle.net/4QtS5/



// 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);
});

[#83747] Wednesday, August 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sandra

Total Points: 708
Total Questions: 100
Total Answers: 84

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
sandra questions
Tue, Jun 30, 20, 00:00, 4 Years ago
Sun, May 31, 20, 00:00, 4 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Fri, May 31, 19, 00:00, 5 Years ago
;