I can not have more than one attribute : Am trying to write "onClick" attribute to different classes using java script.

window.onload=function (){
document.getElementsByClassName("sg")[0].setAttribute("onClick", "ga('send', 'event', { eventCategory: 'Submit a form', eventAction: 'Click', eventLabel: 'Contact form submit'});");    

document.getElementsByClassName("sm")[0].setAttribute("onClick", "ga('send', 'event', { eventCategory: 'Submit a form', eventAction: 'Click', eventLabel: 'Contact form submit'});");  
}

The problem is adding an attribute is working only if the all classes were on one page like the code above.But if i want to have the same code on another page which have different classes then non of the code will work for the both pages. and i will have this error in the console(Cannot read property 'setAttribute' of undefined
    at window.onload):

window.onload=function (){
document.getElementsByClassName("sg")[0].setAttribute("onClick", "ga('send', 'event', { eventCategory: 'Submit a form', eventAction: 'Click', eventLabel: 'Contact form submit'});"); 

document.getElementsByClassName("sm")[0].setAttribute("onClick", "ga('send', 'event', { eventCategory: 'Submit a form', eventAction: 'Click', eventLabel: 'Contact form submit'});");   
 
document.getElementsByClassName("sf")[0].setAttribute("onClick", "ga('send', 'event', { eventCategory: 'Submit a form', eventAction: 'Click', eventLabel: 'Contact form submit'});");   
}
