Last active
November 10, 2019 09:52
-
-
Save pickworth/08fb80ed7c60496b1a46d46b1ae7a85d to your computer and use it in GitHub Desktop.
Sort a HTML list using Javascript
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
// Exactly the same thing with less code | |
const myElement = document.querySelector(".office-list"); | |
const officesArray = Array.from(document.querySelectorAll(".office")); | |
myElement.innerHTML = '' | |
officesArray | |
.map(element => element.innerHTML) | |
.sort() | |
.forEach(content => myElement.innerHTML += `<li>${content}</li>`); |
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
// Select the element with the class of | |
// office-list and store it in the myElement variable | |
const myElement = document.querySelector(".office-list"); | |
// Selects all of the elements with class name of "office" | |
// and store in the officeList variable. | |
const offices = document.querySelectorAll(".office"); | |
const officesArray = Array.from(offices) | |
// take some content and add a new list item to myElement | |
function addListItemToMyElement(content) { | |
myElement.innerHTML = myElement.innerHTML + "<li>" + content + "</li>" | |
} | |
// take an element and return it's content (innerHTML) | |
function takeInnerHTML(element) { | |
return element.innerHTML | |
} | |
// set the content of myElement to be blank | |
myElement.innerHTML = '' | |
// Take the innerHTML from each item in the array | |
// sort it | |
// then, for each item, as list item to myElement | |
officesArray | |
.map(takeInnerHTML) | |
.sort() | |
.forEach(addListItemToMyElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment