0

Is it possible sort div by content item? For example I have one div that has 3 child div.In each child div exists different numbers of span elements. Can I sort this div?

<div id="mydiv">
    <div>
        <span>1</span>
        <span>2</span>
    </div>
    <div>
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
    </div>
    <div>
        <span>1</span> 
    </div>
</div>
garfbradaz
  • 3,424
  • 7
  • 43
  • 70
  • 1
    Possible duplicate of [jquery .sortable() on
    ](https://stackoverflow.com/questions/9659966/jquery-sortable-on-div)
    – Jacob H Jul 25 '17 at 13:05
  • @JacobH: There's no indication of jQuery UI in the question above. – T.J. Crowder Jul 25 '17 at 13:06
  • @T.J.Crowder There's no indication of much of anything. – Jacob H Jul 25 '17 at 13:07
  • 1
    It's not at all clear what you're asking. Separately, be sure you've [searched thoroughly](/help/searching) and done other research, made an attempt to solve the problem, etc. Right now this reads as "write this for me" which isn't usually well-received on SO. – T.J. Crowder Jul 25 '17 at 13:07
  • @JacobH: Which is no reason for voting/suggesting to close it as a duplicate of something that there's no indication it duplicates. (It *is* a good reason to vote-to-close. :-) ) – T.J. Crowder Jul 25 '17 at 13:07
  • I'd rather offer a solution in the vote to close than none at all. Otherwise I would have simply voted to close based on low quality. – Jacob H Jul 25 '17 at 13:08
  • why i get -1 ??? – gh darvishani Jul 25 '17 at 13:09
  • You get -1 because people looking at your post see that you are asking a question that could be solved if you did *any* research first. – Jacob H Jul 25 '17 at 13:10
  • Possible duplicate of [How to sort numbers in javascript](https://stackoverflow.com/questions/44605188/how-to-sort-numbers-in-javascript) – Ismail Farooq Jul 25 '17 at 13:11
  • i change title ... i want sort by item count – gh darvishani Jul 25 '17 at 13:13

1 Answers1

2

You can convert the nodeList to an array, and then use sort:

var myDiv = document.getElementById("mydiv")
var elements = [].slice.call(myDiv.children);

var sorted = elements.sort(function(a, b) {
  return a.children.length - b.children.length;
})

console.log('SORTED', sorted)

To apply this sorting to the DOM, simply reappend these elements:

sorted.forEach(el=>myDiv.appendChild(el));

in action

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Sventies
  • 2,314
  • 1
  • 28
  • 44