selector是利用css selector来匹配选择页面元素的,所以要理解selector首先应该对css selector有所理解,下面是css2 selector的语法,当然很多浏览器只是支持其中的一部分,prototype 中的selector主要支持tag选择器、class选择器和id选择器,还有属性(attribute)选择器,基本上包含我们平时所用的所有类型
the following table summarizes css2 selector syntax, 详细的可以看http://www.w3.org/tr/rec-css2/selector.html:
patternmeaningdescribed in section
* matches any element. universal selector
e matches any e element (i.e., an element of type e). type selectors
e f matches any f element that is a descendant of an e element. descendant selectors
e > f matches any f element that is a child of an element e. child selectors
e:first-child matches element e when e is the first child of its parent. the :first-child pseudo-class
e:link e:visited matches element e if e is the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited). the link pseudo-classes
e:active e:hover e:focus matches e during certain user actions. the dynamic pseudo-classes
e:lang(c) matches element of type e if it is in (human) language c (the document language specifies how language is determined). the :lang() pseudo-class
e + f matches any f element immediately preceded by an element e. adjacent selectors
e[foo] matches any e element with the “foo” attribute set (whatever the value). attribute selectors
e[foo=”warning”] matches any e element whose “foo” attribute value is exactly equal to “warning”. attribute selectors
e[foo~=”warning”] matches any e element whose “foo” attribute value is a list of space-separated values, one of which is exactly equal to “warning”. attribute selectors
e[lang|=”en”] matches any e element whose “lang” attribute has a hyphen-separated list of values beginning (from the left) with “en”. attribute selectors
div.warning html only. the same as div[class~=”warning”]. class selectors
e#myid matches any e element id equal to “myid”. id selectors
selector中包含selector对象和类,
selector对象具有下面两个方法:
match(element):元素是否与本selector匹配,在element中已经介绍了
findelements(parentnode):parentnode中所有匹配本selector的子孙元素列表
使用方法也很简单 var s=new selector(expression); s.match(element); s.findelements($(element)),其中expression可以是如下方式 div、#id、.class、div#id、div[attribute]、div[attribute=fff]、div[attribute!=sdf]
其中selector也有几个静态方法,它们分别是:
matchelements(elements, expression):返回elements中符合expression的元素列表
findelement(elements, expression, index):返回elements中符合expression的元素列表中索引为index的元素
findchildelements(element, expressions):找出element的子孙元素中符合expressions的元素列表,其中expressions是一个expression数组,其中的expression支持div li.#id形式
$$方法:只是简单的调用return selector.findchildelements(document, $a(arguments))
虽然selector有这么多方法,但是大部分都是内部调用的,我们一般都很少使用,因为我们有个一个方便的方法$$,对于绝大部分情况已经足够了