js package acquired DOM

function $(selector){
  // Get the first character
  var firstLetter = selector.charAt(0);
  // The first character of judge
  switch(firstLetter){
    // # id name was;
    case '#' : return idSelector(selector);
    break;
    // was class;
    case '.' : return classSelector(selector);
    break;
    default : return tagNameSelector(selector);
  }
  //idSelector
  function idSelector(idS){
    return document.getElementById(idS.substring(1));
  }
  //tagNameSelector;
  function tagNameSelector(tagNameS){
    return document.getElementsByTagName(tagNameS);
  }
  //classSelector
  function classSelector(classS){
  // compatible processing
  if(docuent.getElementsByClassName){
    return document.getElementsByClassName(classS.substring(1));
  }else{
    // array placed dom node
    was arr = [];
    // If the browser is not compatible getElementsByClassName
    // get all elements on the page
    var arrTag = document.getElementsByTagName('*');
    // use regular matches to find the corresponding label
    var reg = new RegExp('(^|\\s)'+classS.substring(1)+'($|\\s)','g');
    // loop through all of the labels
    for(var i = 0 , k = arrTag.length ; i < k ; i++){
    // If the label has the name of the class with a push into an array
      console.log(arrTag[i].className);
      if(reg.test(arrTag[i].className)){
        arr.push(arrTag[i]);
      }
   }
  return arr;
    }
  }
}

Guess you like

Origin www.cnblogs.com/bruce-w/p/11456601.html