Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can document.createElement be combined

Tags:

javascript

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);
like image 584
davidcondrey Avatar asked May 18 '26 04:05

davidcondrey


2 Answers

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 :)

like image 68
Sampson Avatar answered May 20 '26 16:05

Sampson


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.

like image 34
Warren R. Avatar answered May 20 '26 18:05

Warren R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!