Best way to find DOM elements with css selectors

后端 未结 5 821
感情败类
感情败类 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:23

    Here is a nice snippet i've used some times. Its really small and neat. It has support for the all common css selectors.

    http://www.openjs.com/scripts/dom/css_selector/

    0 讨论(0)
  • 2020-11-29 06:32

    No there's no built in way. Essentially, if you decide to go without jQuery, you'll be replicating a buggy version of it in your code.

    0 讨论(0)
  • 2020-11-29 06:35

    Creating a selector engine is no easy task. I would suggest learning from what already exists:

    • Sizzle (Created by Resig, used in jQuery)
    • Peppy (Created by James Donaghue)
    • Sly (Created by Harald Kirschner)
    0 讨论(0)
  • 2020-11-29 06:37

    In addition to the custom hacks, in recent browsers you can use the native methods defined in the W3C Selectors API Level 1, namely document.querySelector() and document.querySelectorAll():

    var cells = document.querySelectorAll("#score > tbody > tr > td:nth-of-type(2)");
    
    0 讨论(0)
  • 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.
    };
    
    0 讨论(0)
提交回复
热议问题