Prototype - $() Method



The most commonly used and convenient function, $(), provides an easy way of getting a handle on a DOM element.

Syntax

$(id | element)

OR

$((id | element)...)

Return Value

  • Found HTMLElement.
  • In case it finds more than one elements, then it returns array of HTML elements.

Here is an old way of writing Javascript statement to get a node of DOM.

node = document.getElementById("elementID");

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

node = $("elementID");

Example

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function test() {
            node = $("firstDiv");
            alert(node.innerHTML);
         }
      </script>
   </head>

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

Output

Fetching Multiple Values Using $()

The $() function is also more powerful than document.getElementById() because the ability to retrieve multiple elements is built into the function.

Another nice thing about this function is that you can pass either the id string or the element object itself, which makes this function very useful when creating other functions that can also take either form of argument.

Example

In this example, we see the $() function now returning an array of our elements, which can then be accessed with a simple for loop.

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

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

Output

prototype_utility_methods.htm
Advertisements