Reputation: 1854
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.
Upvotes: 0
Views: 5693
Reputation: 696
You could expand your condition from just e
to (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 use hasClassName(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?
Upvotes: 3
Reputation: 95488
The code as it stands, will work if you pass in a string. However, if you want to be sure that you're only passing in a DOM element (it's better to be strict), you can modify your code to this:
function isNode(o){
return (
typeof Node === "object" ? o instanceof Node :
typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
}
function isElement(o){
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
typeof o === "object" && o.nodeType === 1 && typeof o.nodeName==="string"
);
}
var changeColorTo = {
grey: function(e) {
isNode(e) || isElement(e) ? (e.className = "grey") : "" ;
},
...
}
For more information on how isNode
and isElement
work, take a look at this stackoverflow answer. This code will also ensure that you won't try to change the className
attribute of a null
or undefined
variable since the first condition in each of those functions (o instanceof Node
and o instanceof HTMLElement
) will fail, which ensures that isNode
and isElement
will return false for null
and undefined
values.
Upvotes: 1