JQuery: how to skip all children of a div

I am trying to skip all the elements in this div and display the results (C # code, which I will use later) on 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 create this string value:

 HtmlElement.CreateNode("test").AddNode(CreateNode("a").addText("aVal")).AddNode(CreateNode("c").AddNode(CreateNode("cc").addText("ccVal")) 

Right now I see this jquery in place, but I'm not sure how to expand 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)" }); 
+7
source share
4 answers

Here is a more complete example than the 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); }); 
+6
source

JsFiddle example

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

+16
source

You loop direct children of your div, not all children. To do this, use this code:

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

You can use id div to get all child elements like this:

 $('#youDivId').children().each(function(){ alert(this.value); }); 
+1
source

All Articles