Created
April 11, 2018 21:51
-
-
Save ben-heath/ca5d0e7b95d689da3b2271cf6609555b to your computer and use it in GitHub Desktop.
Reorder html elements by data attribute using JS
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
<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