view raw
Dmitry Parzhitsky Dmitry Parzhitsky - 10 months ago 26
Javascript Question

Is there any unified way to set both `innerHTML` and `onclick` to one element?

I'm trying to create element using its JSON description.
JavaScript now provides this:

elem.innerHTML = "Text"; // works fine
elem.onclick = "alert(true)"; // doesn't work

elem.setAttribute("innerHTML", "Text"); // doesn't work
elem.setAttribute("onclick", "alert(true)"); // works fine

Unfortunately, I'm not allowed to print

elem.onclick = function() {alert(true)};

Is there any unified way to set both
to one element?
Like this:

var props = {"innerHTML":"Text", "onclick":"alert(true)"};
var elem = document.createElement("BUTTON");

for (property in props) elem[property] = props[property];
/* or */
for (property in props) elem.setAttribute(property, props[property]);
/* or maybe something else */


You cold use the Function constructor:

elem.onclick = new Function('', 'return alert(true);');

See working Fiddle

EDIT: I couldn't found a unified way to do this to both events and attributes on an element, but since all events starts with on keyword, you could check if it's an event or attribute on your for loop:

for (property in props) {
    if(property.substr(0,2) === 'on') {
        //an event
        elem.setAttribute(property, props[property]); 
    else {
        //an attribute
        elem[property] = props[property];

See working Fiddle