javascript - Sort div by content item -


is possible sort div content item? example have 1 div has 3 child div.in each child div exists different numbers of span elements. can sort 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> 

you can convert nodelist array, , 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 sorting dom, reappend these elements:

sorted.foreach(el=>mydiv.appendchild(el)); 

in action


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -