Last active
December 18, 2022 13:12
-
-
Save amelieykw/230026b0f7171492685a9344fda26e97 to your computer and use it in GitHub Desktop.
[jQuery sort divs - by DOM element name] #jQuery #javascript #sort_divs #html #css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
body { | |
background: #eee; | |
font-family: sans-serif; | |
} | |
.box { | |
background: red; | |
height: 200px; | |
width: 200px; | |
} | |
.box h1 { | |
color: white; | |
font-size: 3.5em; | |
text-align: center; | |
} | |
.box h2 { | |
color: black; | |
font-size: 2.5em; | |
text-align: center; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="wrap"> | |
<button id="alphBnt">Alphabetical</button> | |
<button id="numBnt">Numerical</button> | |
<div id="container"> | |
<div class="box"> | |
<h1>B<h1> | |
<h2>10.35</h2> | |
</div> | |
<div class="box"> | |
<h1>A<h1> | |
<h2>100.05</h2> | |
</div> | |
<div class="box"> | |
<h1>D<h1> | |
<h2>200</h2> | |
</div> | |
<div class="box"> | |
<h1>C<h1> | |
<h2>5,510.25</h2> | |
</div> | |
</div> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var $divs = $("div.box"); | |
$('#alphBnt').on('click', function () { | |
var alphabeticallyOrderedDivs = $divs.sort(function (a, b) { | |
return $(a).find("h1").text() > $(b).find("h1").text(); | |
}); | |
$("#container").html(alphabeticallyOrderedDivs); | |
}); | |
$('#numBnt').on('click', function () { | |
var numericallyOrderedDivs = $divs.sort(function (a, b) { | |
return $(a).find("h2").text() > $(b).find("h2").text(); | |
}); | |
$("#container").html(numericallyOrderedDivs); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment