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:
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;
}