function _(e) {
if (typeof e == 'string') {
if (e.charAt(0) == '#') {
return document.getElementById(e.slice(1));
} else if (e.charAt(0) == '.') {
var c = document.getElementsByClassName(e.slice(1));
return (c.length==1)?c[0]:c;
} else {
var t = document.getElementsByTagName(e);
return (t.length==1)?t[0]:t;
}
} else {
console.log('Error. Not a valid string in _.');
}
}
_.prototype.hide = function() {
//testing
console.log(this)
}
The function works fine, but when i try to add the method hide and try and call it like _('#menu').hide();, it throws the error: TypeError: Object #<HTMLDivElement> has no method 'hide' What have I misunderstood?
And yes, I did google this problem, I just don’t get it. A hint would be much appreciated.
You use a constructor function as a regular function, so it won’t create an object, it will just return what you specified.
You can use it as a regular function, but then you need to call itself as a constructor to create the object to return, and handle when it’s used as a constructor:
You might consider to always use an array for the elements, even when it’s a single element. Right now the
elementsproperty will either be an element or an array of elements, so you have to check for this every time you use it…