I need to call a function inside innerHTML and this is my try but it doesn't work.
category.find({}, function(err, docs) {
docs.forEach(function(d) {
var id = d._id
document.getElementById('result').innerHTML += '<li onclick=insert(id)>' + d.name + '</li>'
})
})
function insert(id){
alert(id + "Inserted")
}
Here is the HTML Part:
<div id="result"></div>
I need to call a function inside innerHTML and this is my try but it doesn't work.
category.find({}, function(err, docs) {
docs.forEach(function(d) {
var id = d._id
document.getElementById('result').innerHTML += '<li onclick=insert(id)>' + d.name + '</li>'
})
})
function insert(id){
alert(id + "Inserted")
}
Here is the HTML Part:
<div id="result"></div>
Share
Improve this question
edited Mar 9, 2019 at 23:41
demo
6,24519 gold badges83 silver badges158 bronze badges
asked Mar 9, 2019 at 22:47
zippaxzippax
3243 gold badges5 silver badges13 bronze badges
3
-
Is
d._id
a number? – Ele Commented Mar 9, 2019 at 22:50 -
3
try this :
'<li onclick=\'insert("' + id + '")\'>' + d.name + '</li>'
– A. El-zahaby Commented Mar 9, 2019 at 22:51 - @ A. El-zahaby your code also work, thanks ^^ – zippax Commented Mar 9, 2019 at 23:15
2 Answers
Reset to default 6Variables in onclick
attributes are evaluated in the global scope, you can't refer to local variables. You need to replace id
in the string with the actual value of the id
variable. You can do this with a template literal.
const docs = [{
id: "FgrbV2NTp72ie6xj",
name: "Joe"
}, {
id: "agfadsfasdfq23",
name: "Fred"
}];
docs.forEach(function(d) {
document.getElementById('result').innerHTML += `<li onclick="insert('${d.id}')">${d.name}</li>`
});
function insert(id) {
alert(id + " Inserted")
}
<ul id="result"></ul>
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".