After Set "classname" To Created Button, How Will That "class" Can Be Called
Solution 1:
Since you are binding "click" event to buttons (which are having "trying" class) on load of the html page, newly added buttons(which were not there in page load) will not bind the "click" event.
One thing you can do is, binding the "click" event while you are adding the new button like below.
functionaddbutton(obj) {
newtag = document.createElement("button");
newtag.classList.add("trying");
newtag.innerHTML = "WHen I button that button it doesnt call function grupla() function";
newtag.addEventListener('click', grupla)
divarea = document.getElementById("kanban_1");
divarea.appendChild(newtag);
};
var elems = Array.from(document.querySelectorAll('.trying'));
elems.forEach(el => el.addEventListener('click', grupla));
functiongrupla() {
var index = elems.indexOf(this);
alert(index);
};
<buttonclass="trying">Which Class</button><buttonclass="trying">Which Class</button><buttonclass="trying">Which Class</button><buttonclass="trying">Which Class</button><buttonclass="trying">Which Class</button><buttonclass="trying">Which Class</button><buttononclick="addbutton(this)">add</button><divid="kanban_1"></div>
Even though the "click" event is fireing for new buttons now,you will not have the expected index values. it will be always -1, since the "elems" array is creating while page loading and new buttons are not in your array at the time page loads.
Solution 2:
The first comment you got was the answer: Event binding on dynamically created elements?.
You currently register the event listener for all existing .trying
elements, but you must add an event listener which listens for new elements as well. Whether you do this with jQuery or not is up to you. Remove jQuery as tag then if you don't want it.
You also got a comment refering you to event delegation. Please click on links people give you. For example there is one tutorial link inside one of the links you probably want to read and implement (it is the pure JavaScript solution): How JavaScript Event Delegation Works
Post a Comment for "After Set "classname" To Created Button, How Will That "class" Can Be Called"