Can combine document.createElement

Multiple items can be created without overwriting document.createElement()

each time.

document.createElement("article");
document.createElement("footer");
document.createElement("header");
document.createElement("hgroup");
document.createElement("nav");

      


It would be great..

document.createElements("article,footer,header,hgroup,nav");

      

or

var elems = ["article","footer","header","hgroup","nav"];
document.createElement(elems);

      

+3


source to share


2 answers


You can create an array of the tag names of the elements you want:

var names = ["article", "footer", "header", "hgroup", "nav"];

      

Then use Array.map to create an array of the created elements:



var elements = names.map(document.createElement, document);

      

However, you have to keep in mind that internally this still calls the function createElement

over and over again using a loop. This looks a little better in your code.

EDIT: You need to specify the argument this

as document

, so createElement

it can be called in the correct context.

+3


source


You can 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 documentFragment

, which you could add as a child anywhere in your DOM.

I don't know why you would like to do this though :)

+4


source







All Articles