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 🙂
I’d probably use a
documentFragmentandforEachon your Array.You can shim older browsers with the patch from MDN.
.forEach()patch from MDNHere’s another solution that uses
.reduce()instead.Since
previs always the last return value (or the seeded value for the first iteration), and sinceinsertBeforereturns thecurritem inserted, for each iteration, theprevis always the lastcurr..reduce()patch from MDN