I've fiddled with many snippets, but this is the closest I have so far:
function Q(a){
if(typeof a=="string"){
var b=a[0],c=a.substring(1);
return b=="#"?document.getElementById(c):b=="."?document.getElementsByClassName(c):document.getElementsByTagName(a);
}
}
Q.setClass=function(b){a.className=b}
I want to be able to do Q("#ID").setClass("testClass");
How can I do this?
asked Sep 23, 2014 at 15:22
Jacob Pedersen
3572 gold badges4 silver badges13 bronze badges
1 Answer 1
There's no object-function hybrid in your question. You want an Q (constructor/factory) function that yields an object which has a setClass (method) function.
This can for example be done like this:
function Q(el) {
if (typeof el=="string") {
var b = el.charAt(0),
c = el.substring(1);
el = b=="#"
? [document.getElementById(c)]
: b=="."
? document.getElementsByClassName(c)
: document.getElementsByTagName(a);
}
return {
setClass: function(cls) {
for (var i=0; i<el.length; i++)
el[i].className = cls;
}
};
}
answered Sep 23, 2014 at 15:45
Bergi
671k162 gold badges1k silver badges1.5k bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Jacob Pedersen
I sorted it out with @Felix Kling in the comments, but I'm accepting yours as he did not post as an answer (and your answer states it a bit more clearly). Thanks!
lang-js
Q, which implementssetClass.{this:resp}has no significance, other than setting the object's propertythistoresp. It doesn't impact the other function'sthisvalue. Maybe you just wantconsole.log(resp)inside that function.