Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ira Salem
10,331 Pointstake each .animal in the .animals list and reorder it by the area (width * height) of the rendered DOM element, then alp
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Exercise</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js"></script>
</head>
<body>
<p>take each .animal in the .animals list and reorder it by the area (width * height) of the rendered DOM element, then alphabetically by the name of the animal</p>
<ul class="animals">
<li class="animal zebra">Zebra</li>
<li class="animal aardvark">Aardvark</li>
<li class="animal cow">Cow</li>
<li class="animal pushmepullyou">Pushmepullyou</li>
<li class="animal hippopotamus">Hippopotamus</li>
</ul>
</body>
</html>
1 Answer
rydavim
18,814 PointsYou can use JavaScript's sort() method with a compare function that addresses both of those values. The MDN page has good examples of this.
If you're using vanilla JavaScript, keep in mind that you can't sort an HTMLCollection, so you'll need to create an array of those list items before you sort them.
You'll likely want to make use of the offsetHeight and offsetWidth properties in order to determine the area of your elements. You can read about those here and here.
Once you've sorted the array, you'll need to add the elements to the page in the new order. You could use innerHTML and outerHTML properties to help you with this.
Let me know if you have trouble. This is certainly doable in vanilla JavaScript, but it might be simpler if you're able to use jQuery.
Edit - If you do end up having trouble, could you post your CSS file as well? With no styles, the area of these items will all be the same, so it's a bit of an odd thing to sort by.