Search code examples
javascriptprototypejs

Prototype Js Multiple Selector


This is my css path:

#product_composite_configure .entry-edit .buttons-set.a-right .scalable

How do I select this using prototype js ? I want to add a new attribute to this item.

This doesn't work:

<script type="text/javascript">
    $$('#product_composite_configure .entry-edit .buttons-set.a-right .scalable').setAttribute("test","test");
</script>

Thx

[UPDATE]

This doesn't work too:

$$('div#product_composite_configure div.entry-edit div.buttons-set button.scalable').setAttribute("test","test");

Solution

  • The $$() selector returns an array of the selected elements. So you would need to iterate over the array or user the built-in iterator invoke().

    for example

    $$('.css_class').invoke('writeAttribute','checked',true);
    

    or your CSS selector

    $$('#product_composite_configure .entry-edit .buttons-set.a-right .scalable').invoke('writeAttribute',"test","test");
    

    I used writeAttribute() instead of setAttribute() as it works in all browsers PrototypeJS supports

    There are a few other ways to make this work as well

    $('product_composite_configure').down('.entry-edit .buttons-set.a-right .scalable').writeAttribute('test','test');
    
    $$('#product_composite_configure .entry-edit .buttons-set.a-right .scalable')[0].writeAttribute('test','test');
    

    It all depends on your HTML structure and what your desired behavior is. If you are only going to target one element then using the id lookup with down() probably would work better. If you are going to have multiple child elements within the #product_composite_configure element then using the $$() selector with invoke() would mean any new elements would be affected as well without rewriting the script.