Search code examples
javascriptfunctionsummarize

summarize functions in js


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?


Solution

  • 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