yeppe yeppe - 5 months ago 17
Javascript Question

Js/Jquery dynamically add child element class name based on parent class occurence

I have a html page that has, 3 div with class name as "

xyz
", Now, On page load
($(document).ready(function())
for each occurring of div "xyz" I want to introduce an inner html/child element as "
<div class="childxyz###"></div>
" where
###
represents the position number of occurrence of parent class xyz . For instance, the first occurrence of parent class xyz the child class name would be "
childxyz1
", second occurrence it would be
childxyz2
and so on.

Can someone suggest a simple solution for this?

Initial page

<div class="xyz">
//appending inner html and pass value 1 as xyz is the first occurrence
</div>

<div class="xyz">
//appending inner html and pass value 2 as xyz is the first occurrence
</div>

<div class="xyz">
//appending inner html and pass value 3 as xyz is the first occurrence
</div>


The final page when the Jquery/JS script runs should look like this.

<div class="xyz">
<div class="childxyz1">
</div>
</div>

<div class="xyz">
<div class="childxyz2">
</div>
</div>

<div class="xyz">
<div class="childxyz3">
</div>
</div>


<div class="xyz">
<div class="childxyz1">
</div>
</div>

<div class="xyz">
<div class="childxyz2">
</div>
</div>

<div class="xyz">
<div class="childxyz3">
</div>
</div>

lsv lsv
Answer
allNodes = document.getElementsByClassName("xyz");
for(var i=0;i<allNodes.length;i++){
    newNode = document.createElement("div");
    newNode.className = "childxyz" + (i+1);
    allNodes[i].appendChild(newNode);
}

this?