var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
var target = $(this);
var id = target.attr("id"); // Get the ID
target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());
I use it for add an similar item for array in ShujuQiu project. However, when it's cloned, all ID the same with the original one. I need to update all IDs to make them unique. Otherwise, Javascript will be confused.
$('form').on('click', '.add_record_array_element', function(event) {
console.log("DEBUG:: add record array element!")
// Find the first parent with class "record_array_element"
item = $(this).parents('.record_array_element').first()
// Record cell
cell = item.parent();
// Clone
new_item = item.clone()
// Add prefix to all IDs to make them uniq. https://stackoverflow.com/questions/16465694
var time = new Date().getTime();
new_item.find("[id]").each(function() { // Select all elements with an ID
var target = $(this);
var id = target.attr("id"); // Get the ID
target.attr("id", time+"_"+id); // Set the id
});
// Append
cell.append(new_item)
return event.preventDefault();
});