javascript - Add array of elements to dom -
i have 5 div's
created in html, , want add of them div
wrapper created in javascript. tried looping through 5 div's
via for-in
loop, append div
child of wrapper
.
for reason, for
loop changes 5 div's
order , doesn't append of them in wrapper
. how can add div's
wrapper
, keeping (html) order, using javascript?
(please don't post jquery answers because isn't question. want javascript answers only.)
var wrapper = document.createelement('div'), myclass = document.getelementsbyclassname('myclass'); myclass[0].parentelement.appendchild(wrapper); wrapper.id = 'wrapper'; (var key in myclass) { if (!myclass.hasownproperty(key)) continue; wrapper.appendchild(myclass[key]); }
#wrapper { border: 2px solid green; color: brown; }
<div class="myclass">first</div> <div class="myclass">second</div> <div class="myclass">third</div> <div class="myclass">fourth</div> <div class="myclass">fifth</div>
the document.getelementsbyclassname
method returns htmlcollection
-object, similar array, in has numeric keys should used.
e.g. for (var = 0; < myclass.length; ++i)
once use incremental numeric index, you'll notice behaves same key in myclass
, rather logical, key
is numeric index.
what happening htmlcollection
represents elements in document order (a called live list, reflects changes in dom) , moving them around appending them wrapper element (hence order within htmlcollection
changes too).
there several tricks work around this, 1 closest current setup walk through htmlcollection
end start , insertbefore
instead of appendchild
for (var len = myclass.length - 1; len >=0; --len) { wrapper.insertbefore(myclass[len], wrapper.firstchild); }
this works because wrapper (in example) after elements you're moving it, therefor not changing order of elements.
there (easier) approach: document.queryselectorall
. queryselectorall
method returns (static) nodelist
, can safely assume order not change while move nodes around.
the syntax (imho) more convenient getelementsbyclassname
, uses css selectors
(much popular javascript framework won't mention)
Comments
Post a Comment