HTML changes using element.setAttribute ("onclick", "alert ('Test');") and element.onclick = "alert ('Test');";

I was surprised by comparing the following cases:

button = document.getElementById("addSugerenciaButton"); if (button != null) { button.onclick = "post_to_url('" + addSugerenciaURL + "', idBuzon', '" + id + "');"; } button = document.getElementById("removeBuzonButton"); if (button != null) { button.onclick = function() { if (!confirm(removeSugerenciaMessage)) { return false; }; post_to_url(removeBuzonURL, 'idBuzon', id); }; } button = document.getElementById("editBuzonButton"); if (button != null) { button.setAttribute("onclick","post_to_url('" + editBuzonURL + "', 'idBuzon', '" + id + "');"); } 

Just the latter seems to have changed the HTML (at least by checking Firebug), while the others, although working correctly, did not display any onclick event in the editBuzonButton element.

Any ideas why this is happening?

+4
source share
3 answers

Yes. setAttribute adds an attribute to a DOM node element. For the onclick attribute, there is a side effect under the covers, also adding an onclick event handler, which is created by compiling the attribute value into a javascript function.

Assigning a function to the onclick property of an element directly binds the handler, but does not automatically add the DOM node attribute.

It is now possible that there are browsers that do not distinguish between adding an attribute and binding a guide. But keep in mind that while modifying a document may create script objects as a side effect, the opposite should not be the case: programmatically creating DOM structures may or may not modify the HTML underlying the document in accordance with the browser you are using.

+8
source

Although we all know that the most standard way to set the onclick event inside an HTML element is through element.onclick = "alert('Example');"; ,

Wrong.

You should use addEventListener / attachEvent .

For instance:

 if (element.addEventListener) { element.addEventListener('click', handler, false); } else if (el.attachEvent) { element.attachEvent('onclick', handler); } 
+2
source

In JavaScript in browsers, it's much better for you to have nothing to do with attributes if you can avoid this, which you can almost always do. For event handler attributes, IE behaves differently for all other browsers (see Why doesn't the onclick property set with setAttribute work in IE? For a discussion of this). Just use properties wherever you are, and if you do not need multiple event handlers, the easiest option is to use the old DOM0 event handler properties and make sure you assign a function to them. In this case, using your last example:

 button.onclick = function() { post_to_url(editBuzonURL, 'idBuzon', id); }; 
+1
source

Source: https://habr.com/ru/post/1300764/


All Articles