Question

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)"
});
Was it helpful?

Solution

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

OTHER TIPS

jsFiddle Example

$('#testDiv').find('*').each(function() {
     // do stuff
});

You are looping through the direct children of your div, rather than all the children. To do so, use this code:

$('div#testDiv *').each(function(){
    // Your Code
});

You can use the div id to get all the children in the following way:

$('#youDivId').children().each(function(){
     alert(this.value);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top