Use Prototype to select all elements by class

Prototype has a number of handy utility methods. One of my favorites is the “$$” method, which allows you to select elements by class name. As with most other Prototype functions, this one can be chained to do some really cool stuff.

For this example. we have a table row that has multiple cells. Some of the cells contain input fields. We want to select all elements of type ‘input’ that have a class name of ‘MyClass’, and that are nested inside of that row element. Here’s the code:

    //update all input fields with class MyClass under this row
    var searchStr = '#' + thisRowId + ' input.MyClass';
    var results = $$(searchStr);
    results.each(function(elem){
        //call helper function to do other cool stuff
        elem = updateElementWithCoolStuff(elem);
     });

Notice that we used a variable name for the element id to build a search string. In this case, the variable ‘thisRowId’ could be passed as a function parameter:

var searchStr = '#' + thisRowId + ' input.MyClass';

You could also specify the element id directly. In this case, the row element id is named, surprisingly, ‘rowId’:

var searchStr = '#rowId input.MyClass';

For more detail, check out the Prototype site.

Tags: ,

Leave a Reply

You must be logged in to post a comment.