Skip to content

Instantly share code, notes, and snippets.

@ben-heath
Created April 11, 2018 21:51
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 ben-heath/ca5d0e7b95d689da3b2271cf6609555b to your computer and use it in GitHub Desktop.
Save ben-heath/ca5d0e7b95d689da3b2271cf6609555b to your computer and use it in GitHub Desktop.
Reorder html elements by data attribute using JS
<script>
/*
* This simple script will take multiple html elements, like a group of <li> or <span> or anything,
* and reorder them by the data attribute.
* Example:
* The script will reorder this:
* <span data-test="1">Number 1</span>
* <span data-test="4">Number 2</span>
* <span data-test="3">Number 3</span>
* <span data-test="2">Number 4</span>
*
* into this:
* <span data-test="1">Number 1</span>
* <span data-test="2">Number 4</span>
* <span data-test="3">Number 3</span>
* <span data-test="4">Number 2</span>
*
* add the target withing the querySelectorAll('CSS SELECTOR GOES HERE')
*/
Array.prototype.slice.call(document.querySelectorAll('.column-1 span[data-test]')).sort(function(a, b) {
// Add the data attribute in both of these as well
a = a.getAttribute('data-authorOrder');
b = b.getAttribute('data-authorOrder');
return a.localeCompare(b);
}).forEach(function(a) {
a.parentNode.appendChild(a);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment