Last active
November 24, 2016 09:42
-
-
Save iolloyd/ed2b6bab74397e6e2a9b to your computer and use it in GitHub Desktop.
remove non-elements from parent node
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>permuteChildren()</title> | |
<script type="text/javascript"> | |
// receives the id of the parent | |
function permuteChildren(nodeId) { | |
// Check if node is of the type 'Element' | |
// return false if not | |
var node = document.getElementById(nodeId); | |
if (node.nodeType != 1) { | |
return false; | |
} | |
// Collect child nodes that are the correct type | |
var children = [].slice.call(node.childNodes); | |
var elementChildren = []; | |
for (var i=0; i<children.length; i++) { | |
if (children[i].nodeType == 1) { | |
elementChildren.push(children[i]); | |
} | |
} | |
children = elementChildren; | |
// Remove attached children before | |
// randomly re-inserting them again | |
while (node.firstChild) { | |
node.removeChild(node.firstChild); | |
} | |
// Insert correct children in a random order | |
var max = children.length; | |
// Build a list of ints and then shuffle them | |
// using the Fisher-yates algorithm | |
var range = Array.apply(null, Array(max)).map(function (_, i) {return i;}); | |
var idx = range.length; | |
var rndx; | |
var tmp; | |
while (0 !== idx) { | |
rndx = Math.floor(Math.random() * idx); | |
idx -= 1; | |
tmp = range[idx]; | |
range[idx] = range[rndx]; | |
range[rndx] = tmp; | |
} | |
for (var i=0; i < max; i++) { | |
node.appendChild(children[range[i]]); | |
} | |
return true; | |
} | |
// this is to show the method running | |
window.onload = function() { | |
permuteChildren('ul'); | |
} | |
</script> | |
</head> | |
<body> | |
<!-- | |
You may use this HTML space for the tests. However, please clean it up before submitting your work. | |
--> | |
<ul id='ul'> | |
<li>Lloyd</li> | |
<li>Lloyd</li> | |
<li>Lloyd</li> | |
Moore | |
<li>Moore</li> | |
ok | |
</ul> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment