0

I'm trying to append an ID to div elements, but it seems if there is already an ID it replaces the existing. I'm at a loss.

$(document).ready(function(){
                $("div").each( function(i){
                    $(this).attr({ id: " num_" + ++i });
                })
            });
Jarod Thornton
  • 401
  • 1
  • 7
  • 24

3 Answers3

1

You can do it like below:

$(document).ready(function(){
     $("div").each( function(i){
           $(this).attr({ id: $(this).attr("id") + " num_" + ++i });
     })
});
Furkan Başaran
  • 1,927
  • 2
  • 19
  • 28
  • Furkan Başaran, that did the trick, thank you! Now the next issue is if there is no existing ID it's appending "unidentified." I am also experiencing some some jQuery version conflict. I get no errors, but in this example you can see where the mobile menu is not working http://sandbox.iemajen.com/ where the append ID is running, and in this example where it is not but the mobile menu is working - http://jacobsladderky.com/ – Jarod Thornton Nov 19 '15 at 21:42
0

A div element can only have one identifier and this identifier must be unique. So you can't append an id.

The Javatar
  • 695
  • 5
  • 15
0

An element in html have atmost single id. To solve this problem use customised attributes. Start using 'data-id' and use them as the normal html attributes. If you want to add more ids you just increment number. like... input id='name' data-id='username'

taruntejae
  • 410
  • 4
  • 14