Prototype - $$() Method



The $$() method parses one or more CSS filtering expressions, analogous to the ones used to define CSS rules, and returns the elements that match these filters.

Syntax

$$(cssRule...);

Return Value

An array of HTML elements.

Example

Here is an old way of writing Javascript statement to get all the nodes of DOM with name div.

nodes = document.getElementsByTagName('div');

Using $$(), we can shorten it up as follows −

nodes = $$('div');

Following is same as $('contents'), only it returns an array anyway.

$$('#contents');

Example

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

Output

More Examples

Following returns all links inside the element of ID "contents" with a rel attribute.

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

Following returns all links with a href attribute of value "#" (eyeew!).

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

Following returns all links within the elements of ID "navbar" or "sidebar".

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

Following returns all links, excluding those whose rel attribute contains the word "nofollow".

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

Following returns all even rows within all table bodies.

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

Following returns all DIVs without content (i.e., whitespace-only).

$$('div:empty');
prototype_utility_methods.htm
Advertisements