How to set new id attribute with jQuery?

To implement this, extract id from attr() and use replace() to replace the id attribute.


Following is the code −

<!DOCTYPE html>
<html lang="en">
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
   <div id="first-name">
   $('[id*="-"]').each(function () {
      console.log('Previous Id attribute: ' + $(this).attr('id'));
      $(this).attr('id', $(this).attr('id').replace('-', '----'));
      console.log('Now Id Attribute: ' + $(this).attr('id'));

To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.


This will produce the following output −

Following is the value on console −