Monday, May 20, 2024
77
rated 0 times [  84] [ 7]  / answers: 1 / hits: 19111  / 15 Years ago, wed, may 20, 2009, 12:00:00

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 ).


More From » css-selectors

 Answers
154

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.
};

[#99497] Friday, May 15, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenandwightb

Total Points: 241
Total Questions: 95
Total Answers: 111

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;