Skip to content Skip to sidebar Skip to footer

After Set "classname" To Created Button, How Will That "class" Can Be Called

I got getting class 'index' from data but the problem is that : When I add new button, it doesnt call 'class index' Whe I click it.. Where is the mistake?

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"