JSFiddle - React, Tailwind, and code Playground
HTML
<input type='button' value='Change color' />
<div id='para'>
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
Some random text is displayed here
</div>
JavaScript
$('input').click(function(){
var para = $('#para');
var charArray = $('span', para);
// case: No span (Initial String)
if (charArray.length === 0) {
var html = para.html();
var newArr = [];
var len = html.length;
for (var i=0; i<len; i++) {
newArr.push('<span>' + html[i] + '</span>');
}
html = newArr.join('');
para.html(html);
charArray = $('span', para);
}
// Reset all spans
$.each(charArray, function(i, value) {
value.style.color = '';
});
var paralen = charArray.length;
for (var i=0; i<50; i++) {
var pos = Math.floor(Math.random()*paralen);
charArray[pos].style.color = 'red';
}
});