Kapil Sharma Kapil Sharma - 1 month ago 6x
jQuery Question

Make duplicate ids unique using jquery

I have html files that are auto-generated from a process. Unfortunately, that process creates some

with duplicated id's. Is there a way to convert these id's into unique id's by adding an integer at the end?

I can't remove or hide those `div's.


It's certainly possible, you get use .each() and select the elements by their id attribute:

    $(this).attr('id', $(this).attr('id') + i);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">test</div>
<div id="foo">test</div>
<div id="foo">test</div>

This will change the HTML to:

<div id="foo0">test</div>
<div id="foo1">test</div>
<div id="foo2">test</div>