Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign an unique id to every element created with insertAdjacentHTML

I’m trying to create a page where when you click a button a div element is created, but I want to assign a unique id to that div element so I can access it later somehow. How do I assign it a unique id along with creating it?

the code:

<button onclick="addingItem()">click me</button>
<div id="hello">

</div>

the script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function addingItem(){
let html = "<div style='color:tomato'>Item</div>";
document.getElementById("hello").insertAdjacentHTML("afterbegin", html);
}

this is how I would create element but how do I assign it a unique id please help

>Solution :

try this

var count = 1;
function addingItem(){
  let html = "<div id='fruit-'" + count + " style='color:tomato'>Item</div>";
  document.getElementById("hello").insertAdjacentHTML("afterbegin", html);
  count= count+=1;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading