Daniels Jirgensons Daniels Jirgensons - 23 days ago 9
jQuery Question

Ordering appended classes with Jquery

I want to ask, is this possible to order appended classes? For example, in my JSFiddle i want to get on mobile look

Lorem ipsum dolor sit amet
when Im appending classes.

There's my JQuery

$(".cont-1, .cont-2, .cont-3, .cont-4").clone().prependTo(".mobile-content");


P.S. There's no way to change class order in
.content

Answer

You could use an array of selectors, and prepend one by one

['.cont-1', '.cont-2', '.cont-3', '.cont-4'].reverse().forEach(function(s) {
	$(s).clone().prependTo(".mobile-content");
});
div.content>div{display:inline}
div.mobile-content>div{display:inline;margin:0 5px 0 0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Original look:<br />
<div class="content">
  <div class="cont-2">ipsum</div>
  <div class="cont-1">Lorem</div>
  <div class="cont-4">sit amet</div>
  <div class="cont-3">dolor</div>
</div>
<br />Mobile look:<br />
<div class="mobile-content">
  
</div>

Or sort by classname

$(".cont-1, .cont-2, .cont-3, .cont-4").clone().sort( (a,b) => 
	a.className.localeCompare(b.className)
).prependTo(".mobile-content");
div.content>div{display:inline}
div.mobile-content>div{display:inline;margin:0 5px 0 0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Original look:<br />
<div class="content">
  <div class="cont-2">ipsum</div>
  <div class="cont-1">Lorem</div>
  <div class="cont-4">sit amet</div>
  <div class="cont-3">dolor</div>
</div>
<br />Mobile look:<br />
<div class="mobile-content">
  
</div>

Comments