I've been attempting to colorize each word using jQuery and give them a colored background. I came across a solution, but it only seems to work for the HTML content, not the input field in the search bar. Below is an example of what I found:
HTML
Some content
<div>Another content
<input id="search" type="text" value="dsfdsfdsf sdf dsfsdfsfs">
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac turpis
</p>
Content in body
jQuery
//The main point here is that you need to replace only the contents of the text node, not all the HTML parts
var colours = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'gray'];
var lastC;
jQuery('*').contents().each(function () {
// Not a text node or there is no content to replace
if (this.nodeType != 3 || !this.nodeValue.trim()) {
return;
}
// Replace the value of the text node
$(this).replaceWith(this.nodeValue.replace(/\w+/g, function (part) {
var c = colours[Math.floor(Math.random() * colours.length)];
while (c == lastC) {
var c = colours[Math.floor(Math.random() * colours.length)];
}
lastC = c;
return '<span style="background-color: '+c+';">' + part.split("").join("") + '</span>'
}))
});
I attempted to change jQuery('*')
to jQuery('#search')
, but it didn't work.
Live example https://jsfiddle.net/7hs9mgLp/2/
What should I do to fix this issue?