1

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
bibangamba
  • 1,463
  • 1
  • 19
  • 23
  • Why are you using event delegation? If you don't know what that is, you definitely need to learn about it (since you are using it). If you know what it is you basically already have your answer. – Felix Kling May 23 '16 at 15:21
  • @bibangamba [This](http://stackoverflow.com/a/24053931/4790490) may answer your query. – Hardik Pithva May 23 '16 at 15:22

1 Answers1

2

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339