Meek Meek - 2 months ago 9
jQuery Question

Understanding and using 'this' in jQuery function

I have a function that I would like to apply to different elements - or rather, different selectors creating different contexts. How can I modify the below function to use

this
, instead of specifying the
$('#themes')
selector inside the getClass function?

The code:

$('#themes').change(function(e) {
getClass(this, e);
});

function getClass() {
var classToAdd = $('#themes').find('option[value]:selected').map(function() {
return this.value;
}).get().join(' ');
var allClassess = $('#themes').find('option[value]').map(function() {
return this.value ? this.value : null;
}).get().join(' ');
$('#result').removeClass(allClassess).addClass(classToAdd);
}


See fiddle here.

Answer

The event has a currentTarget property that's exactly what you're looking for, and no need to pass this to it... in fact, just reconfigure the binding like this:

$('#themes').on('change', getClass);

function getClass (event) {
  var themes = $(event.currentTarget);
  var classToAdd = themes.find('option[value]:selected').map(function() {
    return this.value;
  }).get().join(' ');

  var allClassess = themes.find('option[value]').map(function() {
    return this.value ? this.value : null;
  }).get().join(' ');

  $('#result').removeClass(allClassess).addClass(classToAdd);
}
Comments