Kapil Sharma Kapil Sharma - 2 months ago 7
jQuery Question

Make duplicate ids unique using jquery

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

div
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.

Answer

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

$("div[id='foo']").each(function(i){
    $(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>
Comments