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)"
});
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.
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.
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.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
You can use the div id to get all the children in the following way:
$('#youDivId').children().each(function(){
alert(this.value);
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With