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?
var elements = ['header', 'nav', 'section', 'article', 'aside', 'footer'];
for (var i = 0; i < elements.length; i++) {
document.createElement(elements[i]);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With