JSFiddle - React, Tailwind, and code Playground
by lbstr
HTML
<p>Let's highlight random elements from this list: </p>
<ul id="a">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
<li>H</li>
</ul>
JavaScript
function selectRandomFromList($list, num){
var $children = $list.children(),
len = $children.length,
a = [],
o = {},
r,
$items = $([]);
if (!len) { return $items; }
if (num >= len) { return $children; }
// Build an array of unique indices
while (a.length < num) {
r = Math.floor(Math.random() * len);
if (!o.hasOwnProperty(r)) {
o[r] = 1;
a.push(r);
}
}
// grab the items
while (num--) {
$items = $items.add($children.eq(a.pop()));
}
return $items;
}
(function(){
var $list = $('#a'),
$results = $('#results'),
$rand = selectRandomFromList($list, 3);
$rand.css({"background-color":"yellow", "font-weight": "bold"});
})()