curly_brackets
curly_brackets

Reputation: 5598

Unique NAME to clone() elements

How do I give an unique NAME or other ATTR to a element that is cloned?

Thank you in advance.

Upvotes: 0

Views: 464

Answers (3)

Greg Swinde
Greg Swinde

Reputation: 11

Use Math.random:

$('.some_element').each(function() {
    var id = (Math.floor(Math.random()*10000000000000000));
    $(this).clone().attr('id', id);
});

Or, if you'd like a "handle" on the original element, you could create a new id in this format:

ORIGINAL_ELEMENT_ID + SEPARATOR + RANDOM_NUMBER

E.g.,

$('.some_element').each(function() {
    var id = [
        this.id, 
        (Math.floor(Math.random()*10000000000000000))
    ].join('-');
    $(this).clone().attr('id', id);
});

Upvotes: 1

Archan Mishra
Archan Mishra

Reputation: 905

A hack-ish way to do this would be to use a global counter and keep incrementing it by One before adding the value to the name of the cloned element.

ex.

var count =1;
func some_func() {
     var cloneElement = $(form).clone();
     cloneElement.attr('name', cloneElement.attr('name') + count++);
}

Upvotes: 0

Calum
Calum

Reputation: 5316

$('.some_element').clone().attr('id','some_unique_id');

Upvotes: 0

Related Questions