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:
Return Value:
- An array of HTML elements.
Example:
Here is old way of writing Javascript statement to get all the node of DOM with name div.
nodes = document.getElementsByTagName('div');
|
Using $$(), we can shorten it up as follows:
Following is same as $('contents'), only it returns an array anyway.
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>
|
To understand it in better way you can Try it yourself.
More Examples:
Following returns all links inside the element of ID "contents" with a rel attribute
Following returns all links with a href attribute of value "#" (eyeew!)
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)
|