Reputation:
I have the following javascript code:
function changeButtonState(targetSelector, action, iconClass) {
var $target = $(targetSelector);
var $targetSpan = $(targetSelector + ' span');
$targetSpan.removeClass('sprite-blank').addClass(iconClass);
How can I make it so that the $targetSpan.removeClass(..).addClass
only work if the iconClass has a
value when the function is called. I guess what I am confused about is do I check if it is defined
or do I check if it has a length of 0 or more?
Upvotes: 4
Views: 3050
Reputation: 5265
It would be best if you check for undefined
as well.
function changeButtonState(targetSelector, action, iconClass) {
var $target = $(targetSelector);
if (typeof iconClass !== "undefined" && iconClass) {
var $targetSpan = $(targetSelector + ' span');
$targetSpan.removeClass('sprite-blank').addClass(iconClass);
}
}
Update Even though this is a very old answer, it is still relevant. Therefore, i would like to update my answer with an improved one based on @jeremy's comment.
function changeButtonState(targetSelector, action, iconClass) {
var $target = $(targetSelector);
//this will not throw exception since iconClass is implicitly declared through the input parameter
if (iconClass) {
var $targetSpan = $(targetSelector + ' span');
$targetSpan.removeClass('sprite-blank').addClass(iconClass);
}
}
Upvotes: 3
Reputation: 10057
This would allow the user (most likely you) to specify whether or not you want it to be active by either giving it a falsey value or a truthy value. You may also want to check if it's undefined by using the typeof
operator.
if(iconClass) {
$targetSpan.removeClass('sprite-blank').addClass(iconClass);
}
Upvotes: 1