Best way to find DOM elements with css selectors

后端 未结 5 846
感情败类
感情败类 2020-11-29 06:19

What\'s the easiest way to find Dom elements with a css selector, without using a library?

function select( selector ) {
 return [ /* some magic here please          


        
5条回答
  •  伪装坚强ぢ
    2020-11-29 06:40

    These days, doing this kind of stuff without a library is madness. However, I assume you want to learn how this stuff works. I would suggest you look into the source of jQuery or one of the other javascript libraries.

    With that in mind, the selector function has to include a lot of if/else/else if or switch case statements in order to handle all the different selectors. Example:

    function select( selector ) {
     if(selector.indexOf('.') > 0) //this might be a css class
       return document.getElementsByClassName(selector);
     else if(selector.indexOf('#') > 0) // this might be an id
       return document.getElementById(selector);
     else //this might be a tag name
       return document.getElementsByTagName(selector);
     //this is not taking all the different cases into account, but you get the idea.
    };
    

提交回复
热议问题