bibangamba bibangamba - 6 months ago 18
jQuery Question

Assigning a jquery object to a variable doesn't work as expected

Can someone explain why one of these versions of code works and the other fails?

This doesn't work:

var classForSelectedElement = "hightlight";
var prevSelect = $(".form-element");
var $selectedElement = $("div").on("click", ".form-element",function(e){
prevSelect.removeClass(classForSelectedElement);
$(this).addClass(classForSelectedElement);
});


Whereas this works:

var classForSelectedElement = "hightlight";
var $selectedElement = $("div").on("click", ".form-element",function(e){
$(".form-element").removeClass(classForSelectedElement);
$(this).addClass(classForSelectedElement);
});


Why?

Answer

Presuming that the .form-element elements are appended to the DOM dynamically after load (due to your usage of a delegated event handler) then the first example doesn't work as you are attempting to retrieve the .form-element on load of the page before they exist.