Rodrigo Siqueira
Rodrigo Siqueira

Reputation: 375

Javascript Elements Selector

I am creating a Javascript Selector so that it will facilitate the manipulation of those elements in another methods.

My function is being called this way:

//  Selecting three groups of elements in context 'document'
myFunc(["p", "div#id", "ul li"], document);

My function, so far, populates an array representing the elements to be selected:

//  Representation corresponding to the selection above
matches[0] = [["p"]]
matches[1] = [["div", "#id"]]
matches[2] = [["ul"], ["li"]]

Although I tried, I can't get any of these elements but the simplest: "p".

Any tips or help?

Upvotes: 1

Views: 595

Answers (1)

jfriend00
jfriend00

Reputation: 708036

DOM searches for items matching a CSS selector is a solved problem. I can see no reason to reinvent that wheel and deal with all the different browsers and with performance optimizations. For modern browsers, just use document.querySelectorAll() and pass it a legal CSS selector.

For compatibility with old browsers (like IE7), you can pick up a ready-made and tested selector library. If you'll be doing lots of DOM manipulation, then you may want something like jQuery which has a cross browser selector engine built in and support for lots of other DOM manipulation. In jQuery, your selector would be this:

// returns jQuery object that has array of DOM objects in it
var objects = $("p, div#id, ul li");

Or, if you just want a proven selector library, you can pick up Sizzle (which is the engine used internally by jQuery). In Sizzle, it would be:

// returns array of DOM elements
var objects = Sizzle("p, div#id, ul li");

If you really want to make your own selector matching code, you're going to have to write code to parse your select, then write code to walk the entire DOM, then create code to match each type of selector with a given object in the DOM. I can see no reason why one would want to reinvent all that code when free, tested and performance optimized libraries are already available for you to use. You could literally be done in minutes.

Or, if you don't need IE 7 support, you can just use document.querySelectorAll(). If you do need IE 7 support, there are some polyfills available that will give you document.querySelectorAll() in IE7, but at that point, you may want to just use one of the better prebuilt selector libraries to solve this problem that are more performance optimized too.

// returns a NodeList (an array-like list of nodes)
var objects = document.querySelectorAll("p, div#id, ul li");

If you really want to build your own selector library, please explain why and exactly what selectors you need to support so we might better advise how to proceed.

Upvotes: 3

Related Questions