Bora Dan Bora Dan - 1 month ago 21
Javascript Question

one Var, multiple createElement

I'm creating a html structure from js.

var e = document;

// HTML Tree
$this.append(
$(e.createElement('div')).addClass('wood-bottom'),
$(e.createElement('div')).addClass('jalendar-wood')
.append(
$(e.createElement('div')).addClass('jalendar-pages')
.append(
$(e.createElement('div')).addClass('pages-bottom'),
$(e.createElement('div')).addClass('header'),
$(e.createElement('div')).addClass('total-bar'),
$(e.createElement('div')).addClass('days')
)
)
);


and there are so many
createElement('div')
statements.

Is there a better solution for this method?
If I define
var e = document.createElement('div')
, it doesn't work like I want.

Answer

What about a custom function?

var div = function(klass){return $(document.createElement('div')).addClass(klass)};

    // HTML Tree
    $this.append(
        div('wood-bottom'), 
        div('jalendar-wood')
            .append(
                div('jalendar-pages')
                    .append(
                        div('pages-bottom'),
                        div('header'),
                        div('total-bar'),
                        div('days')
            )
        )
    );
Comments