Is there a shorthand way to document.createElement multiple elements?

Issue

Is there a shorthand method in JS to document.createElement when you’re creating a bunch of elements.

To maximize usage of HTML5, and still make sites work in older browsers, I tend to have something like this snippet of JS in every site I do:

// Allows HTML5 tags to work in older browsers
document.createElement('header');
document.createElement('nav');
document.createElement('section');
document.createElement('article');
document.createElement('aside');
document.createElement('footer');

Is there a way to add them via one statement — comma separated or something similar?

Solution

var elements = ['header', 'nav', 'section', 'article', 'aside', 'footer'];
for (var i = 0; i < elements.length; i++) {
    document.createElement(elements[i]);
}

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published