This will randomly add italics to words in a div. It uses a randomized array of 0 to [word count] numbers to determine which words should be italicized in the main text.
Adjust numWordsToItalicize
to change the number of words italics are applied to.
Fiddle
Javascript
var words = $('#words');
var initialText = words.html();
function italics(){
var wordArr = initialText.split(' ');
var randomArray = getRandomArray(wordArr.length);
numWordsToItalicize = 100;
for(var i = 0; i < numWordsToItalicize && i < wordArr.length; i++) {
wordArr[randomArray[i]] = '<span class="italic">' + wordArr[randomArray[i]] + '</span>';
}
words.html(wordArr.join(' '));
}
function getRandomArray(length) {
var arr = [];
for(var i = 0; i < length; i++) { arr.push(i); }
return shuffleArray(arr);
}
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
$('#doItalics').on('click', function(){
italics();
});
HTML
<input id="doItalics" type="button" value="Italicize!" />
<div id="words">
A large amount of text...
</div>
CSS
.italic {
font-style: italic;
}