Search code examples
jqueryclone

Jquery Clone a selector and modify option id


<select id="one">
    <option id="one_val_a" value="one">one</option>
    <option id="two_val_a" value="two">two</option>
    <option id="three_val_a" value="three">three</option>
</select>

<span id="pin"></span>

How could I clone #one, make its id #two, and have its options ids as #one_val_b, #two_val_b, etc.

$('#one').clone(true, true).attr('id', 'two').appendTo('#pin');

That will atleast change the ID of the clone, but now how do change its options ids?

Jsfiddle: http://jsfiddle.net/C2zCZ/2/


Solution

  • Here's another way, using a regex to replace the option id attributes, so it doesn't matter how many options the original select had:

    $('#one').clone(true, true)
        .attr('id', 'two').appendTo('#pin')
        .find("option").each(function() {
            $(this).attr("id", $(this).attr("id").replace(/\_a$/, "_b"));
        });
    

    Example fiddle