Closing Javascript and DOM Builder

I am creating a DOM constructor that I am working successfully, but now I am trying to assign some abbreviated functions to div()e("div")

Here is my code:

//assign these objects to a namespace, defaults to window
(function(parent) {

/**
* Creates string of element
* @param tag The element to add
* @param options An object of attributes to add
* @param child ... n Child elements to nest
* @return HTML string to use with innerHTML
*/
var e = function(tag, options) {
    var html = '<'+tag;
    var children = Array.prototype.slice.apply(arguments, [(typeof options === "string") ? 1 : 2]);

    if(options && typeof options !== "string") {
        for(var option in options) {
            html += ' '+option+'="'+options[option]+'"';
        }
    }

    html += '>';
    for(var child in children) {
        html += children[child];
    }
    html += '</'+tag+'>';
    return html;
}

//array of tags as shorthand for e(<tag>) THIS PART NOT WORKING
var tags = "div span strong cite em li ul ol table th tr td input form textarea".split(" "), i=0;
for(; i < tags.length; i++) {
    (function(el) { //create closure to keep EL in scope
        parent[el] = function() {
            var args = Array.prototype.slice.call(arguments);
            console.log(args);
            args[0] = el; //make the first argument the shorthand tag
            return e.apply(e,args);
        };
    })(tags[i]);
}

//assign e to parent
parent.e = e;
})(window);

What is currently happening, the args array changes every time I call one of the shortened functions, and I assume that something should happen, this closure is somewhere, so the args array that I created is not affected every time call. Here is the result of unit tests:

div (div (span ("Content")), span ()) expected: <div><div><span>Content</span></div><span></span></div>result:<div><span></span></div>

div (div (span (e ("b", e ("b", e ("b")))), span ())) Expected: <div><div><span><b><b><b></b></b></b></span><span></span></div></div>result:<div></div>

+3
3

, , args.unshift(el);

0

,

for(var el in tags) {

. tags - , , for (... in ...).

for(var el = 0; el < tags.length; el++) {

... .

+1

@MvanGeest - for..in . javascript. , for..in. , , , , .

@Anurag - forEach IE8 ( 9), , .

0
source

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


All Articles