简体   繁体   中英

How can I clone and change all ID's of a table with jQuery?

I want to clone a table and change all its ID's adding a prefix.

In the snippet below I change all tr elements ID's adding the prefix my_ , using .find('tr').each(function() .

With jQuery, how can I add a prefix name to all ID's of a table during the clone?

 var $newTable = $('table.copyable:first').clone(); $newTable.removeClass('copyable'); $newTable .find('tr') .each(function() { $(this).attr('id', 'my_'+$(this).attr('id')); }); $('#list-player-songs').html(''); $newTable.appendTo($('#list-player-songs')); 
 table.copyable { background: antiquewhite; } table td { border:1px solid; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3>Original table</h3> <table class="copyable"> <tbody class="sortable"> <tr id="track251"> <td><div data-track-name="love.mp3" id="play251"></div></td> <td id="song-url251">love</td> </tr> <tr id="track241"> <td><div data-track-name="hate.mp3" id="play241"></div></td> <td id="song-url241">hate</td> </tr> <tr id="track233"> <td><div data-track-name="think.mp3" id="play233"></div></td> <td id="song-url233">think</td> </tr> </tbody> </table> <h3>Copied elements</h3> <div id="list-player-songs"></div> <hr/> <br/><br/><br/> 

Search for all ID's and use attr(function) which will in itself do an each internally

$newTable
    .find('[id]')
    .attr('id', function(_, id){
       return 'new-prefix' + id;
    })

You could search for every element that has the id attr like this:

$newTable
    .find('[id]')
    .each(function() {
        $(this).attr('id', 'my_'+$(this).attr('id'));
    });

That way, it will change the id of every element that has an id set.

Elements that don't have an ID set, wont be changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM