In below code, I pass an HMTL element and check whether parameter passed is null or not using ternary operator. If it is not null, I change the className of the passed element.
var changeColorTo = {
grey: function(e){
e ? (e.className = "grey") : "" ;
},
red: function(e){
e ? (e.className = "red") : "" ;
},
green: function(e){
e ? (e.className = "green") : "" ;
},
blue: function(e){
e ? (e.className = "blue") : "" ;
}
};
The above code works fine except when I pass any random string like
changeColorTo.grey("random");
It doesn’t cause any harm. But I am wondering is above code correct? Do I miss anything? or is there any better way to achieve the same result?
Thank you.
You could expand your condition from just
eto(e && e.className). That should prevent script errors resulting from passing in random junk or even non-element nodes.Better, implement that condition as
function hasClassName(e) { return ... }and usehasClassName(e)as your test.EDIT: Replaced less-than-fully-compatible
(typeof e=="object") && ('className' in e)condition, per comments. See also How do I check if an object has a property in JavaScript?