Hi, I would like to use the following function only on the "a" elements contained in the div "myDiv".
This is the code I have been using so far:
$$('a[class="active"]').each(function(element) {
element.removeClassName("active");
});
Hi, I would like to use the following function only on the "a" elements contained in the div "myDiv".
This is the code I have been using so far:
$$('a[class="active"]').each(function(element) {
element.removeClassName("active");
});
You can do that two ways:
1) Look up myDiv and then use Element#select:
$('myDiv').select('a[class="active"]').each(...);
or
2) Use an ID selector with a descendant selector with $$:
$$('#myDiv a[class="active"]).each(...);
If you want only direct children (not descendants), you could use a child selector (note the >):
$$('#myDiv > a[class="active"]).each(...);
Off-topic #1: The usual way to write a[class="active"] in a selector would be a.active, e.g., "$('myDiv').select('a.active').each(...);".
Off-topic #2: You might also look at the invoke function, which is for calling the same function on each item in an Enumerable object (so for instance, "$('myDiv').select('a[class="active"]').invoke('removeClassName', 'active');"). invoke is nice, short, and expressive, but it's slower than doing it yourself as you did. (It only matters when you get into thousands of elements, though.)