summarize functions in js

1.1k views Asked by At

I would like to summarize some JavaScript functions. For example:

document.getElementByClassName("lamp")[0]; == selector(".lamp")[0];

In this example I haven't problem, my problem is the following code:

selector(".lamp")[0].selector(".school")[1].style.color = "red";

when i run this code console says :

Uncaught TypeError: selector(...)[0].selector is not a function(…)

and this is my selector function :

function selector(string){
  switch (string[0]) {
    case '#':
      string = string.replace('#','');
      return document.getElementById(string);
      break;
    case '.':
      string = string.replace('.','');
      return document.getElementsByClassName(string);
      break;
    case '<':
      string = string.replace('<','');
      return document.getElementsByTagName(string);
      break;
    case '?':
      string = string.replace('?','');
      return document.getElementsByName(string);
      break;
    default:
      console.log('i cant select it --by selector.js--');
  }
}

what do I do?

1

There are 1 answers

0
hamidb80 On BEST ANSWER

you should use prototype:

function selector(string){
  switch (string[0]) {
    case '#':
      string = string.replace('#','');
      return document.getElementById(string);
      break;
    case '.':
      string = string.replace('.','');
      return document.getElementsByClassName(string);
      break;
    case '<':
      string = string.replace('<','');
      return document.getElementsByTagName(string);
      break;
    case '?':
      string = string.replace('?','');
      return document.getElementsByName(string);
      break;
    default:
      console.log('i cant select it --by selector.js--');
  }
}
Object.prototype.selector = function(){
  switch (string[0]) {
    case '#':
      string = string.replace('#','');
      return document.getElementById(string);
      break;
    case '.':
      string = string.replace('.','');
      return document.getElementsByClassName(string);
      break;
    case '<':
      string = string.replace('<','');
      return document.getElementsByTagName(string);
      break;
    case '?':
      string = string.replace('?','');
      return document.getElementsByName(string);
      break;
    default:
      console.log('i cant select it --by selector.js--');
  }
};

this code run correctly without any error