Skip to content

Instantly share code, notes, and snippets.

@nmors
Last active November 10, 2019 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmors/08fb80ed7c60496b1a46d46b1ae7a85d to your computer and use it in GitHub Desktop.
Save nmors/08fb80ed7c60496b1a46d46b1ae7a85d to your computer and use it in GitHub Desktop.
Sort a HTML list using Javascript
// 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>`);
// 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