Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document createElement shortest syntax

I'm looking for the shortest syntax which could provide me the same result as this dojo line:

var divblock5 = dojo.create("div", {className: "barlittle", id: "block5"});

but I want to use plain JavaScript instead of dojo framework. I have a lot of dynamic element creation and I want to make my code short as possible.

like image 970
Jacob Avatar asked May 16 '26 01:05

Jacob


2 Answers

var create = function(element, properties) {
    var elmt = document.createElement(element);
    for (var prop in properties) {
        elmt[prop] = properties[prop];
    }
    return elmt;
}

create("div", {className: "barlittle", id: "block5"});

Or, my personal favorite that simply takes HTML and converts it to a DOM node :

var elmtify(html) {
    var wrapper = document.createElement('div');
    wrapper.innerHTML = html;
    return wrapper.firstChild;
}

elmtify('<div class="barlittle" id="block5"></div>');
like image 177
Tom van der Woerdt Avatar answered May 18 '26 13:05

Tom van der Woerdt


You should check put-selector: https://github.com/kriszyp/put-selector.

like image 35
iH8 Avatar answered May 18 '26 14:05

iH8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!