How can i create unique id for html elements | SoloLearn: Learn to code for FREE!

+3

How can i create unique id for html elements

I am using createelement in javascript but is there any way to make the id of the element new everytime i create the element. For example, the first time i create the id will be "test1" then when i run the code again it will return an element with the id "test2" Is it possible????

6/3/2020 10:20:09 AM

Asef Dian🇧🇩

2 Answers

New Answer

+7

Asef Dian🇧🇩 Hey. Of course you can do that. Here's the solution : <script src="https://cdnjs.cloudflare.com/ajax/libs/node-uuid/1.4.8/uuid.js"></script> Include this in your head tag. Now you can make a unique id each time you run the code. Like so : const id = uuid(); Now use this 'id' as your element's id. That's all :))

+1

uuids are huge, why would you want to create one as the id of an html element? It isn't exactly easy to write... var element = document.getElementById(af2b32ac-6913-4373-9ad9-edd05cae63b1); and how are you going to know what the id is anyway? The uuids will change each time the program runs.