0

How do I reorder dom elements based on the css position left?

I have 3 elements, with left values of 10, 20, and 30 percent, and position: absolute.

In the DOM, they're in the order 20, 10, 30 but I'd like to order them ascending according to the left attribute (10, 20, 30).

All three elements are inside a div with id parent

0

2 Answers 2

1

You'll need to loop through the child elements as an array so that they can be sorted, and then you need to reattach the children in the right order. This can be done in pure JavaScript without jQuery:

var parent = document.getElemntById(parent),
    children = [];

// loop through the child nodes, add them to your array
// and remove them from the parent
for (var i = parent.childNodes.length-1; i >= 0; i--) {
    children.push(parent.childNodes[i]);
    parent.removeChild(parent.childNodes[i]);
}
// sort them based on the left property
children.sort(function(a,b){
    return window.getComputedStyle(a)['left'] - window.getComputedStyle(b)['left'];
});
// add them back to the parent in order
for (var i in children) {
    parent.appendChild(children[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Basically, loop through the DOM elements you want to modify, put them in an array. Then sort the array by the property you want (in this case window.getComputedStyle(elem)['left']) and then re-insert the elements in the order the array tells you to.

Comments

Your Answer

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.