0

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
4
  • 3
    You have to return a wrapper object from Q, which implements setClass. Commented Sep 23, 2014 at 15:25
  • I tried doing this: hastebin.com/vavagazeci.coffee but it didn't work. Could you give me a hint? Commented Sep 23, 2014 at 15:37
  • 2
    Since I don't know what you expect, I can't tell what exactly "didn't work". However, {this:resp} has no significance, other than setting the object's property this to resp. It doesn't impact the other function's this value. Maybe you just want console.log(resp) inside that function. Commented Sep 23, 2014 at 15:39
  • Just a last question: Is it possible to detect if a Q.prototype is issued? I want to return just the response if no command is set. Commented Sep 23, 2014 at 16:16

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.