Question

I currently have two click functions..

  1. Creates clones of the 'parent' div with unique ID's
  2. Creates clones of the 'child' div with unique ID's

My problem is that I cannot get the child div ID's to reset for each parent, as shown below.

I get this...

<div class="parent" id="a1">
  <div id="child-a1-1"></div>
  <div id="child-a1-2"></div>
  <div id="child-a1-3"></div>
</div>

<div class="parent" id="a2">
  <div id="child-a2-4"></div>
  <div id="child-a2-5"></div>
  <div id="child-a2-6"></div>
</div>

Instead of...

<div class="parent" id="a1">
  <div id="child-a1-1"></div>
  <div id="child-a1-2"></div>
  <div id="child-a1-3"></div>
</div>

<div class="parent" id="a2">
  <div id="child-a2-1"></div>
  <div id="child-a2-2"></div>
  <div id="child-a2-3"></div>
</div>

My Code

    var newchildId = 1;
    jQuery('.parent').delegate('.add-child', 'click', function() {
        var parentId = $(this).closest('.parent').attr('id');
        var firstChild = 'child-' + parentid + '-1';
        var newChild = 'child-' + parentid + '-' + newchildId;
        var copy = $("#" + firstChild).clone(true);
        copy.attr('id', newChild );
        $(this).closest('.parent').append(copy);
         newchildId++;
    });
Was it helpful?

Solution

I would restructure the code (and slightly the HTML) to count the actual children present under a given parent rather than use a global counter because the global counter can't possibly keep a separate count for each separate hierarchy:

jQuery(".parent").on("click", ".add-child", function() {
    var parent = $(this).closest('.parent');
    var childs = parent.find(".child");
    var clone = childs.eq(0).clone(true);
    var newID = "child-" + parent.attr("id") + "-" + (childs.length + 1);
    // this sets the text to match the ID just for clarity in the demo
    clone.attr("id", newID).html(newID).appendTo(parent);
});

Working demo with slightly modified HTML: http://jsfiddle.net/jfriend00/j9PT7/


FYI, I switched to .on() which is the more modern way of doing delegated event handlers (assuming you're on jQuery 1.7+).


FYI, you could keep a per-hierarchy counter by using .data("counter") on each parent as you add each child under that parent, but I see no reason to separately manage a counter when you can just see how many children are actually in the DOM itself and base your addition on that.


FYI, with proper use of selectors, there is rarely a need to actually have a monotomically indexing id on each DOM element any more so the real question here is probably why you're trying to do this and what better technique could you use that doesn't require this specially managed id value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top