jQuery class selector not selecting after class change

button, class, javascript, jquery, jquery-selectors

Solution

This only runs once, when the document loads:

$(".exit").click(function(){
    //roomchangefunction
});

At that time, there are no matching elements for `.exit`. So no click handlers are assigned. After that, this never runs again.

Since the elements are dynamically changing, I recommend binding a click handler to a common parent element using `.on()` instead. Something like this:

$(document).on('click', '.exit', function () {
    //roomchangefunction
});

The difference is that the click event is actually assigned to a common parent (in this case `document`, though any common parent element will work such as a `div` which always contains the `.exit` elements). When an element is clicked, the "click" event occurs on that element and all the way up the DOM. So this handler would be invoked. The second argument is a filter, so it looks for elements which match that filter when invoking the handler function.

That way the filter for `.exit` happens when the element is clicked, rather than when the document is loaded, so that elements which are dynamically changed during the life of the document are still handled.

Problem

Im using Javascript to build a button click and puzzle adventure game. The game will allow a series of button commands. When the "go" command is clicked, the buttons change to different exits, and the class is changed to exit, like so: ``` function setExitButtons(){ clearButtons(); for (var i = 0; i < player.currentRoom.exits.length; i++) { var buttoni = button[i]; buttoni.className = "exit"; buttoni.innerHTML = player.currentRoom.exits[i].name; $(buttoni).show(); } } ``` Where clearButtons hides all of the buttons so only the correct ones show, and button[] is the nodelist for the buttons. The class does change when this function is called. I then have another jquery function with a class selector, like so: ``` $(".exit").click(function(){ //roomchangefunction }); ``` The .exit function is not activated when the button with exit class is clicked. I have a document ready function encompassing the whole part. Thoughts?

Original source