javascript iterate array through insertBefore -
i'm trying make code bit more reusable.
currently 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 use array , iterate through items this, however:
var lightbox_elements = []; lightbox_elements.push(lightbox_overlay, lightbox_border, lightbox_content); any ideas next steps are? must in plain js..
thanks :)
i'd use documentfragment , foreach on 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 patch mdn.
here's solution uses .reduce() instead.
[ lightbox_overlay, lightbox_border, lightbox_content ].reduce(function(prev, curr) { return document.body.insertbefore(curr, prev); }, top_element); since prev last return value (or seeded value first iteration), , since insertbefore returns curr item inserted, each iteration, prev last curr.
Comments
Post a Comment