Gabriel Blankenburg
Gabriel Blankenburg

Reputation: 27

issues sorting html elements using only javascript

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)?

Upvotes: 1

Views: 50

Answers (1)

charlietfl
charlietfl

Reputation: 171689

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>

Upvotes: 4

Related Questions