Reputation: 6040
I want to clone a div
using it's id
with many elements inside it which also has their own id
that I want to change after cloning.
Consider this HTML structure:
<div id='wrapper1'>
<p id='test1'>Hello</p>
<p id='my-awesome-id1'></p>
</div>
I found this on SO but it only changes the id
of the main element you cloned and not the children.
Is there a way I could do it so that I could update all of the 1
into 2
and so on?
Upvotes: 0
Views: 1643
Reputation: 1258
You can use a function like this:
function changeIdNumberOnElementAndChildren(element, newIdNumber) {
var $element = $(element),
$elementChildren = $element.children(),
oldId = $element.attr("id"),
newId = (oldId) ? oldId.replace(/\d+$/, newIdNumber) : null;
if (newId) {
$element.attr("id", newId);
}
if ($elementChildren.length > 0) { // recursively call function on children
$elementChildren.each(function(i, child) {
changeIdNumberOnElementAndChildren(child, newIdNumber);
});
}
}
Then simply call it on a clone to change the ids:
$(function() {
var clone = $("#wrapper1").clone();
// below changes the ids so that they end in 559 rather than 1
// (i.e. "wrapper559", "test559" and "my-awesome-id559")
changeIdNumberOnElementAndChildren(clone, 559);
});
Upvotes: 0
Reputation: 207881
This would do it and create a clone like:
<div id="wrapper2">
<p id="test2">Hello</p>
<p id="my-awesome-id2"></p>
</div>
$('div').clone().filter(function() {
$(this).prop('id', $(this).prop('id').replace('1', '2')).children().filter(function() {
return $(this).prop('id', $(this).prop('id').replace('1', '2'))
});
return $(this)
}).appendTo('body')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='wrapper1'>
<p id='test1'>Hello</p>
<p id='my-awesome-id1'></p>
</div>
Upvotes: 3