Unfortunately input
tag words can't have different colors, since text and input are not separate elements, but for other elements you can wrap each word into span
and add style to them, that is how rich content editors are working.
Assume you have <p id="paragraph">Here are few words</p>
and you want to add different colors to each word.
You can split
innerText of #paragraph
and create span for each word and insert result as innerHTML of #paragraph
.
Here is example
var paragrapgh = document.getElementById("paragraph");
var words = paragrapgh.innerText.split(" "); // here I am spliting words by space i.e tokenizing it
var colors = ["red","green","blue","pink", "gold", "yellow", "blueviolet"];
var spans = [];
for(var x = 0; x < words.length; x++){
var color = colors[Math.floor(Math.random()*colors.length)] // geting random color from array;
var span = "<span style='background-color: " + color + ";'>" + words[x] + "</span>"
spans.push(span);
}
// setting colored spans as paragraph HTML
paragrapgh.innerHTML = spans.join(" ");
<p id="paragraph">Here are few words</p>
Also you can use contenteditable
attribute to elements to allow users to edit content of element as it is input.
So you can try to use contenteditable
div with keyup
event and make your styling of words.