I am trying to clone an element, and then traverse through it's child elements and change attributes accordingly, the thing is that I am trying to access the elements via custom attributes using CSS selectors and I can't seem to get it to work, here is what I have thus far,
HTML:
<div id='main_container'>
<div id="container">
<div class="wrapper">
<div><label>... </label></div>
<div><input type="text" id="one" new="one_1" /></div>
</div>
<div class="wrapper">
<div><label>... </label></div>
<div>
<select id="two" new="two_1" >
<option>...</option>
<option>...</option>
</select>
</div>
</div>
<div class="wrapper">
<div><label>... </label></div>
<div>
<select id="three" new="three_1" >
<option>...</option>
<option>...</option>
</select>
</div>
</div>
</div>
<div class="wrapper">
<input type="button" value="add a section" id="button" />
</div>
</div>
jQuery:
$('#button').click(function(){
var clone = $('#container').clone().appendTo('#main_container');
clone.children('["new*=one"]').attr('class', 'one');
clone.children('["new*=two"]').attr('class', 'two');
clone.children('["new*=three"]').attr('class', 'three');
});
.children()
only gets immediate or direct children, you're looking for .find()
here, like this:
$('#button').click(function(){
var clone = $('#container').clone().appendTo('#main_container');
clone.find('[new*="one"]').attr('class', 'one');
clone.find('[new*="two"]').attr('class', 'two');
clone.find('[new*="three"]').attr('class', 'three');
});
You can give it a try here.
Note the moved quotes above as well. .find()
searches any level deep, so all descendants when matching the selector, that's the important difference in this case. Also, to be safe on the attribute though, I'd use data-new
instead, it'll be HTML5 compliant as well.
Another thing to keep in mind is with the code you posted, you're getting duplicate IDs, make sure to remove or change those when cloning.
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