1

I'm trying to make my code a bit more reusable.

Currently I am using:

var top_element = document.getElementById('main');
document.body.insertBefore(lightbox_overlay, top_element);
document.body.insertBefore(lightbox_border, lightbox_overlay);
document.body.insertBefore(lightbox_content, lightbox_border);

I would like to use an array and iterate through the items to do this, however:

var lightbox_elements = [];
lightbox_elements.push(lightbox_overlay, lightbox_border, lightbox_content);

Any ideas what the next steps are? Must be in plain JS..

Thanks :)

asked Jun 5, 2012 at 18:13

1 Answer 1

3

I'd probably use a documentFragment and forEach on your Array.

var frag = document.createDocumentFragment();
[ lightbox_overlay,
 lightbox_border,
 lightbox_content ].forEach(function(el) { frag.appendChild(el); });
document.body.insertBefore(frag, top_element);

You can shim older browsers with the patch from MDN.


Here's another solution that uses .reduce() instead.

[ lightbox_overlay,
 lightbox_border,
 lightbox_content ].reduce(function(prev, curr) { 
 return document.body.insertBefore(curr, prev); 
 }, top_element);

Since prev is always the last return value (or the seeded value for the first iteration), and since insertBefore returns the curr item inserted, for each iteration, the prev is always the last curr.

answered Jun 5, 2012 at 18:22
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.