amine_detter amine_detter - 3 months ago 10
HTML Question

How to add an Id, value and onclick event to a dynamic generated div

i have to add onglets (dev) and affect them an id, value and onclick.
i tried by this way but is not working

function functionDeleteLevel(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
var formData = new FormData();
formData.append("valeur", "deleteLevel");
ajaxPost("/deleteLevel", formData, function (reponse) {
var data = JSON.parse(reponse);
data.forEach(function(level){
var newLi = document.createElement("li");
newLi.value = level.level;
newLi.id = "levelId_"+level.level;
newLi.innerHTML = 'onclick="functionSelectedLevel(this.id)"';
newLi.innerHTML = '<a data-toggle="tab">Niveau'+level.level+'</a>';
s2.appendChild(newLi);
});

});
}

Answer

you can use

newLi.addEventListener('click', function() {functionSelectedLevel(this.id);}) 

or

newLi.onclick = function() {functionSelectedLevel(this.id);};

or - with a bit of a change to functionSelectedLevel

newLi.addEventListener('click', functionSelectedLevel) 

or

newLi.onclick = functionSelectedLevel;

functionSelectedLevel would then be

functionSelectedLevel() {
    // here, the value of this is the element that was clicked
    do things with this.id
}