1

Hi i'm having some issues trying to sort HTML elements with JavaScript... Here is the HTML code:

<div id="sorting">
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
        <span>5</span>
 </div>

and javascript code:

function spanSort(){
    var div = Array.prototype.slice.call(document.getElementById("sorting").children);
    div.sort(function(){
        return 1;
    });
}

I'm trying to inverse the order of the spans to 5,4,3,2,1... but nothing happens. Can I do so still using the sort method or at least without using any loop (I know it works with for loop)?

3
  • 1
    You’re just sorting a copy of a list of elements, you’re not actually modifying the DOM. Commented May 8, 2017 at 1:44
  • Are you trying to reverse the list without regard for the values, or sort based on the values in the elements? Why is your sort function returning 1? That feels like a hack that assumes a certain sort algorithm. Commented May 8, 2017 at 3:16
  • my goal is actually sort them based on the values in the elements, but in this case i'm just trying to reverse the order of the elements to understand how to sort them (that's why it's returning 1) Commented May 8, 2017 at 4:23

1 Answer 1

4

Use Array#reverse() then append the sorted elements. A sort outside the dom has no effect in the dom

var sorting = document.getElementById("sorting")

var div = [].slice.call(sorting.children).reverse();
div.forEach((el)=>{
 sorting.appendChild(el);
});
   
<div id="sorting">
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
        <span>5</span>
 </div>

Sign up to request clarification or add additional context in comments.

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.