views:

236

answers:

4

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 :) */ ]
};

select('body')[0] // body;

select('.foo' ) // [div,td,div,a]

select('a[rel=ajax]') // [a,a,a,a]

This question is purely academical. I'm interested in learning how this is implemented and what the 'snags' are. What would the expected behavior of this function be? ( return array, or return first Dom element, etc ).

+1  A: 

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.

Mehrdad Afshari
To be fair, JQuery isn't the only library that provides selector-style functionality, just the most prominent.
Hank Gay
Yes, of course. By "without jQuery", I mean without an external library of choice.
Mehrdad Afshari
+4  A: 

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.
};
Jose Basilio
Not necessarily - look at Sizzle (jQuery's engine) and you won't see any of this.
J-P
+3  A: 

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)
J-P
Great links! Really interesting. Specially that performance test runner.
Mohsin Hijazee
+3  A: 

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/

alexn