开发者

Clone a div and change the ID's of it and all it's children to be unique

开发者 https://www.devze.com 2022-12-21 17:17 出处:网络
Using JQuery it possible to clone a Div like this and change add a new identifier to it\'s ID and all it\'s children ID\'s?

Using JQuery it possible to clone a Div like this and change add a new identifier to it's ID and all it's children ID's?

For instance I'd like to be able to clone this:

<div id="current_users">
<table id="user_list">
<tr id="user-0">
<td id="first_name-0"&开发者_C百科gt;Jane</td>
<td id="last_name-0">Doe</td>
</tr>
<tr id="user-1">
<td id="first_name-1">John</td>
<td id="last_name-1">Doe</td>
</tr>
</table>
</div>

And have it look like this:

<div id="current_users_cloned">
<table id="user_list_cloned">
<tr id="user-0_cloned">
<td id="first_name-0_cloned">Jan</td>
<td id="last_name-0_cloned">Doe</td>
</tr>
<tr id="user-1_cloned">
<td id="first_name-1_cloned">John</td>
<td id="last_name-1_cloned">Doe</td>
</tr>
</table>
</div>

Or should I just rethink my structure and use rel attributes and reusable class declarations?

Thanks,

Tegan Snyder


$("#current_users").clone(false).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + "_cloned"); });

And watch your events if there are any attached. You'll have to fix them up if they rely on ids.


Unless you actually need to uniquely identify each of those cloned DIV's via code, I would replace your ID's with reusable classes. Otherwise, David Morton's answer looks like it might do the trick.


David Morton had the right answer back in 2010, but I just wanted to update it. jQuery removed .andSelf() in 3.0.0 (see adeneo's answer). The latest and greatest (as of this writing) is .addBack(). So the line would be:

$("#current_users").clone(false).find('*[id]').addBack().each(function () { $(this).attr('id', function(i , id) { return id + "_cloned" + ruleId}) });

If you need to get it back as a string, which was the case for me, add .get(0).outerHTML; to the end.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号