Prototype - $$() 方法

$$() 方法解析一个或多个 CSS 过滤表达式(类似于用于定义 CSS 规则的表达式),并返回与这些过滤器匹配的元素。

语法

$$(cssRule...);

返回值

HTML 元素数组。

示例

以下是编写 Javascript 语句的一种旧方法,用于获取名称为 div 的 DOM 的所有节点。

nodes = document.getElementsByTagName('div');

使用 $$(),我们可以将其缩短如下 −

nodes = $$('div');

以下内容与 $('contents') 相同,只是它返回一个数组。

$$('#contents');

示例

<html>
   <head>
      <title>Prototype examples</title>
      <script type="text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function test() {
            allNodes = $$("div");
            
            for(i = 0; i < allNodes.length; i++) {
               alert(allNodes[i].innerHTML);
            } 
         }
      </script>
   </head>

   <body>
      <div id = "firstDiv" name = "div">
         <p>This is first paragraph</p> 
      </div>
      
      <div id = "secondDiv" name = "div">
         <p>This is another paragraph</p>
      </div>
      
      <input type = "button" value = "Test $()" onclick = "test();"/>
   </body>
</html>

输出

更多示例

以下返回 ID 为"contents"的元素内具有 rel 属性的所有链接。

$$('#contents a[rel]');

以下返回 href 属性值为"#"的所有链接(哇哦!)。

$$('a[href="#"]');

以下将返回 ID 为"navbar"或"sidebar"的元素内的所有链接。

$$('#navbar a', '#sidebar a');

以下将返回所有链接,但不包括 rel 属性包含单词"nofollow"的链接。

$$('a:not([rel~=nofollow])');

以下将返回所有表体中的所有偶数行。

$$('table tbody > tr:nth-child(even)');

以下将返回所有没有内容的 DIV(即,只有空格)。

$$('div:empty');

prototype_utility_methods.html