Prototype setAttribute () does not work with the $$ () selector

I want to change the onclick function of a button inside a div. HTML code below:

<div class="buttons-set" id="payment-buttons-container"> <button type="button" class="button" onclick="payment.save()" id="payment_button"></button> </div> 

I am using the following prototype to change the onlick payment.save () function to something else.

 if(payment_method=='gate') { var e = $$('div#payment-buttons-container button.button'); e.setAttribute('onclick','return false;'); // not working } else { var e = $$('div#payment-buttons-container button.button'); e.setAttribute('onclick','payment.save();'); // not working } 

Which does not work and says "Uncaught TypeError: Object [object HTMLButtonElement] does not have a method of" setAttribute "" But when I use this code if it sets a static button identifier than its working

 if(payment_method=='gate') { $('payment_button').setAttribute('onclick','return false;');// Works } else { $('payment_button').setAttribute('onclick','payment.save();');// Works } 

Where "payment_button" is the identifier of the button I took.

+4
source share
1 answer

The problem is that $$() returns a list of elements matching the CSS selector

try this if you just want the first element to match the selector

 if(payment_method=='gate') { var e = $$('div#payment-buttons-container button.button')[0]; e.setAttribute('onclick','return false;'); // not working } else { var e = $$('div#payment-buttons-container button.button')[0]; e.setAttribute('onclick','payment.save();'); // not working } 

if you want to apply it to all elements that match the CSS selector using the invoke() method

 if(payment_method=='gate') { $$('div#payment-buttons-container button.button').invoke('writeAttribute','onclick','return false;'); } else { $$('div#payment-buttons-container button.button').invoke('writeAttribute','onclick','payment.save();'); // not working } 

the reason I used writeAttribute() instead of setAttribute() is because writeAttribute() is a PrototypeJS method and will work in all browsers supported by PrototypeJS, setAttbribute() is a standard method that is not always available.

+10
source

All Articles