The magical select() function!

In my previous post about the Line-Duplicater I had to find specific tags within a DOM element. As I found nothing in the Utility Methods I had to use the getElementsByTagName() function. But only with this function I couldn’t solve the problem. I also had to use the $A() function to get an array of the elements. The result for all there form input types looked like that:

$A(newRow.getElementsByTagName('select')).invoke('clear');
$A(newRow.getElementsByTagName('textarea')).invoke('clear');
$A(newRow.getElementsByTagName('input')).each(function(elm){
	elm.clear().checked = '';
}); 

Today I accidentally found a new Prototype 1.6 function called select(). With this function I could shorten the selection to the following lines:

newRow.select('select').invoke('clear');
newRow.select('textarea').invoke('clear');
newRow.select('input')).each(function(elm){
	elm.clear().checked = '';
}); 

But even this simplification is way to
Aber selbst diese Vereinfachung ist noch zu complex. The function allows you the select elements with a number of CSS selector. You just have to use multiple parameters with the function:

newRow.select('select', 'textarea', 'input')).each(function(elm){
	elm.clear().checked = '';
}); 

This simplification is not reasonable at all as it makes no sense to set the “checked” attribute to an empty value, but it damages anything.

As you can see the select() function offers a very easy selection within an already selected elements. But the function not only selects the elements, it also extends the elements using the extend() function to offer some additional element function. So the function simplifies the following code:

// a normal call using the getElementsByTagName() function
$A(newRow.getElementsByTagName('input')).map(Element.extend);
// the same call using the select() function
newRow.select('input');

The select() function is in principle the $$() function extended with the combination of the elemtents into an array. So using the function you can safe a lot of extra work hanling selected elements.

Posted by

Bernhard is a full time web developer who likes to write WordPress plugins in his free time and is an active member of the WP Meetups in Berlin and Potsdam.

Leave a Reply

Your email address will not be published. Required fields are marked *