Selecting cloned elements by id fails every other time
Hi all
I've encountered an odd problem and although I worked out a hack to get around it I can't figure out what I did wrong.
I used JQuery to clone() a div (id=div_0) that contains other divs, selects, etc. I change the id on the newly cloned parent div and try to access underlying elements by id as shown below. The JQuery selector fails to find a matching element
every other time (evens work / odds don't)!
I'm no doubt overlooking some basic logic error or there's something subtle in my code that's off. Here's a simplified example:
HTML (enclosing <form> assumed):
-
<div id="div_0">
<select name="select_0" id="select_0">
<option val="0">Zero</option>
<option val="1">One</option>
</select>
</div>
<div id="end_of_form"> </div>
JS
-
function someoneClickedSomething(newIndex) { // newIndex increments with each call
$("#div_0").clone().attr('id', 'div_' + newIndex).insertBefore("#end_of_form"); // works
$("#div_" + newIndex + " select#select_0).attr('id', 'select_' + newIndex); // fails on div_1, div_3, works on div_2, div_4!!
}
Checking further the odd ones did not resolve the selector (e.g. $("div_1 select#select_0") does not find an element while $("div_2 select#select_0") does!). I checked and newIndex is incrementing properly so the problem isn't there.
I'll bet I'm overlooking something basic. Any thoughts appreciated.
Stu