KDX KDX - 14 days ago 4x
CSS Question

How do I randomly apply CSS style using plain Javascript?

I have a few list entries that I would like to randomly highlight, 1 item only with different background and text color.

As shown below with "list 2" highlighted.

<div id="entries">
<ul style="list-style-type: none;">
<li><a href="#1">list 1</a></li>
<li><a href="#2" style="color:#fff; background-color:#000">list 2</a></li>
<li><a href="#3">list 3</a></li>
<li><a href="#4">list 4</a></li>
<li><a href="#5">list 5</a></li>

How can I achieve this using vanilla javascript without the use of jQuery?


Pretty easy (vanilla JS):

// Query entries:
var entries = document.querySelectorAll('#entries ul li a');        

// Clean up entries styles
for(var i = 0; i < entries.length; i++){
      var style = entries[i].style;
      style.backgroundColor = null;
      style.color = null;

// Pick random index
var randomIdx = Math.floor(Math.random() * entries.length);

// Pick random entry's style
var randomEntryStyle = entries[randomIdx].style;

// Set styles
randomEntryStyle.backgroundColor = '#000';
randomEntryStyle.color = '#fff';

JS Bin