I need some help figuring out how to write some jQuery code.
I need to clone a table dynamically onclick. but then I need to change the ids of the table and its child elements each time. as the table can have lots of children it will be to difficult to do this manually. I need a way to change the id’s of all child(all descendants) elements. I will always just add the counter to the id. (I know children will access only the immediate children but I just wanted to try if that works). If you guys know how this can be done in either jQuery or Javascript, please let me know.
<table id="table">
<tr id = "tr" >
<td id="td">
<span id="span" value="hiii">hi</span>
</td>
</tr>
</table>
<button>Clone</button>
<script>
$("button").click(function () {
var table = $("#table").clone(true,true)
table.attr( 'id', function() { return this.id +"1"; })
alert($("#table1").children())
$("#table1").find(*).attr('id', function() { return this.id +"1"; })
table.appendTo("#table")
alert(document.getElementById("tr1"))
alert(document.getElementById("span1").value)
});
</script>
If
elemis the parent of your cloned structure andcntris the counter you said you were maintaining, you can fix all ids in that cloned structure like this:If the ids might already have a cloned number at the end and you want to replace that number, you can do so like this:
So, based on the code you’ve now added to your question, you could do this:
Working example: http://jsfiddle.net/jfriend00/wFu9K/
Note: I also changed the DOM insertion code to
insertAfter(), because you can’t append one table to another the way you were doing (a table would either go after the existing table or inside a cell in the previous table).If you are just trying to add a row, then you need to clone the row, not the whole table.
You could add a cloned row to the existing table with this code: