Jacob Pedersen
Jacob Pedersen

Reputation: 347

Object/Function hybrid

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?

Upvotes: 0

Views: 148

Answers (1)

Bergi
Bergi

Reputation: 665536

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;
    }
  };
}

Upvotes: 1

Related Questions