Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: How to loop through all child elements of a div

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)"
});
like image 870
some_bloody_fool Avatar asked Aug 08 '12 23:08

some_bloody_fool


People also ask

How do you iterate through children in jQuery?

each( (index, element) => { console. log(index); // children's index console. log(element); // children's element }); This iterates through all the children and their element with index value can be accessed separately using element and index respectively.

How do you loop through an element with the same class in jQuery?

Answer: Use the jQuery each() Method You can simply use the jQuery each() method to loop through elements with the same class and perform some action based on the specific condition.

How do you iterate through an element in jQuery?

The . each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.

Which will select all direct child elements in jQuery?

The ("parent > child") selector selects all elements that are a direct child of the specified element.


2 Answers

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

$('#youDivId').children().each(function(){
     alert(this.value);
});
like image 110
befree2j Avatar answered Sep 28 '22 09:09

befree2j


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
});
like image 22
JCOC611 Avatar answered Sep 28 '22 07:09

JCOC611