...as there is nothing to distinguish those divs as they all have the same id and class name...
Ah, but there is! Where they are in their parent. You can get an array of the elements, reverse it, and then append them to the parent, which will move them so that they're in that reverse order:
var container = document.getElementById("container");
var divs = Array.from(container.children);
divs.reverse();
divs.forEach(function(div) {
container.appendChild(div);
});
Live Example:
setTimeout(function() {
var container = document.getElementById("container");
var divs = Array.from(container.children);
divs.reverse();
divs.forEach(function(div) {
container.appendChild(div);
});
}, 800);
.ib {
display: inline-block;
}
<div id="container"><div class="ib">1</div><div class="ib">2</div><div class="ib">3</div><div class="ib">4</div><div class="ib">5</div></div>
Note that I was careful to do the markup so that there wouldn't be any Text nodes in there, because the children
collection only includes Elements, not Text nodes. But if you want to reverse all the children, including text nodes, use childNodes
instead of children
:
setTimeout(function() {
var container = document.getElementById("container");
var divs = Array.from(container.childNodes);
divs.reverse();
divs.forEach(function(div) {
container.appendChild(div);
});
}, 800);
.ib {
display: inline-block;
}
<div id="container">
<div class="ib">1</div>
<div class="ib">2</div>
<div class="ib">3</div>
<div class="ib">4</div>
<div class="ib">5</div>
</div>
Note that I've kept the code to ES5 level (not ES2015+), except that Array.from
is more recent. You can easily polyfill it, or use
var divs = Array.prototype.slice.call(container.children/*or childNodes*/);
instead.