Aleksandar Aleksandar - 2 months ago 6
Javascript Question

Programmatically setting a unique object ID in JavaScript

I have the following code

<div id='show_test'></div>


And

var matches = [{
"category_name": "category_1",
"stock_name": "stock_1",
"supplier_stock": "supplier_stock_1"
}, {
"category_name": "category_2",
"stock_name": "stock_2",
"supplier_stock": "supplier_stock_2"
}, {
"category_name": "category_3",
"stock_name": "stock_3",
"supplier_stock": "supplier_stock_3"
}, {
"category_name": "category_4",
"stock_name": "stock_4",
"supplier_stock": "supplier_stock_4"
}];
matches.forEach(function(i, item) {
var arrayDt = [];
arrayDt[i, item] = {
"category_name": this.category_name,
"stock_name": this.stock_name,
"supplier_stock": this.supplier_stock
};
document.getElementById("show_test").innerHTML += "<div><a id='bt_" + item + "'>click</a></div>";

document.getElementById("bt_" + item).onclick = function() {
show_data(i);
}

console.log(document.getElementById("bt_" + item));
console.log(i);

});

function show_data(data) {
alert(JSON.stringify(data));
}


On the page we show 4 links, when I click on the last link, the script functions as expected. But not the first 3. Why does this not work with the first 3 links?

https://jsfiddle.net/a35wL5ht/

Answer

replace

document.getElementById("show_test").innerHTML += '<div><a href="#" id="bt_' + item + '">click</a></div>';

with

var el = document.createElement("div");
var a =  document.createElement("a");
a.innerHTML = "click";
a.id = "bt_" + item;
el.appendChild(a);
document.getElementById("show_test").appendChild(el);