const docs = [{
id: "FgrbV2NTp72ie6xj",
name: "Joe"
}, {
id: "agfadsfasdfq23",
name: "Fred"
}];
let d = document;
d.g = d.getElementById;
let res = d.g('result');
let fragment = new DocumentFragment();
let el = null;
docs.forEach(function(item) {
el = document.createElement('li');
el.innerText = `${item.name}`;
el.onclick = function(){
alert(`${item.id}` + " Inserted");
};
fragment.appendChild(el);
});
res.appendChild(fragment);
ul{
cursor:default;
}
<ul id="result"></ul>
While innerHTML
is easy to use, according to a discussant here:
...in general, .innerHTML is for small fragments of HTML to be
inserted and parsed into a document ..
So, instead of solving the OP's query with respect to innerHTML
, this solution purposefully avoids it by utilizing DOM manipulation and at the same time makes the desired function available as a handler for an onclick event of an <LI> element. To achieve this end, the code creates a document fragment object. As a result the code is able to add the LI elements as well as the id of each one and set the onclick event-property of each in a function invoked by the docs.forEach()
. Also, I added some CSS to enhance the cursor when user clicks "Joe" or "Fred".