Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 828
Keefer Avatar asked Dec 04 '22 22:12

Keefer


2 Answers

var elements = ['header', 'nav', 'section', 'article', 'aside', 'footer'];
for (var i = 0; i < elements.length; i++) {
    document.createElement(elements[i]);
}
like image 50
Quentin Avatar answered Dec 08 '22 06:12

Quentin


I know you didn't ask for it, but jQuery makes this pretty easy.

var $elems = $("<header/><nav/><section/><article/><aside/><footer/>");
$( "header", $elems ).html("Sweeeeet!");
// etc...

Basically what I've just done is created 6 dom elements and returned them into a jQuery object (which is similar to a node list I suppose). Then I can act on those items however I choose, or even loop through them:

$elems.each( function(){ /* Loopy stuff */ } );

Of course, don't forget to actually add them to the document

$("body").append( $elems );

See also templates for not so ugly dom generation and built in tools.

like image 36
Kevin Peno Avatar answered Dec 08 '22 06:12

Kevin Peno