Can multiple elements be created without rewriting document.createElement() each time..
document.createElement("article");
document.createElement("footer");
document.createElement("header");
document.createElement("hgroup");
document.createElement("nav");
These would be great..
document.createElements("article,footer,header,hgroup,nav");
or
var elems = ["article","footer","header","hgroup","nav"];
document.createElement(elems);
You could create your own method:
function createElements( arr ) {
var fragment = document.createDocumentFragment();
arr.forEach(function creator ( tagname ) {
fragment.appendChild( document.createElement( tagname ) );
});
return fragment;
}
And then call it like this:
createElements( [ "p", "div", "footer" ] );
This returns a documentFragment, which you could then append as a child anywhere in your DOM.
I don't know why you would want to do this though :)
You could create an array of element tag names you want:
var names = ["article", "footer", "header", "hgroup", "nav"];
Then use the Array.map function to create an array of created elements:
var elements = names.map(document.createElement, document);
However, you should keep in mind that internally this still calls the createElement function over and over using a loop. It just looks a bit nicer in your code.
EDIT:
You need to specify the this argument as document so createElement can be called in the correct context.
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