So as the title suggests I've been working on a chrome extension to change the colour of each word in a website (to help with my ADHD reading)
The code I have runs without errors but doesn't seem to do anything. The parts I've commented out is when i was trying to split each paragraph word to word but i gave up on that a bit to temporarily simplify
var paragraph = document.getElementsByTagName("p");
var words = paragraph; //.innerHTML.split(" ");
var colours = ["red", "purple", "blue"];
var spans = [];
for(var i = 0; i<words; i++){
var colour = colours[Math.floor(Math.random()*colours.length)]
var span = "<span style='color:" + colour + ";'>" + words[i] + "</span>"
spans.push(span);
}
//paragraph.innerHTML = spans.join(" ");
words.innerHTML = spans.join(" ");
There are several problems in your code.
getElementsByTagName() returns collection of elements (you have to iterate over it).split() you will get whole content instead of wordsinnerHtml() and split() solution probably won't work with complex HTMLI would like to suggest you different approach. I would find every word with space with regular expression in whole document (or element) and wrap it in span with specific class and style it with CSS. Something like this:
const root = document.querySelector('p');
root.innerHTML = root.innerHTML.replace(/(^|<\/?[^>]+>|\s+)([^\s<]+)/g, '$1<span class="word">$2</span>');
.word:nth-child(1n-1) {
color: green;
}
.word:nth-child(2n-1) {
color: red;
}
.word:nth-child(3n-1) {
color: blue;
}
<p>
some words some words
some words some words
some words some words
</p>
If you want random colors, you can change second parameter of replace with function which is being called every iteration. Something like this:
const root = document.querySelector('p');
const colors = ["red", "purple", "blue"];
root.innerHTML = root.innerHTML.replace(
/(^|<\/?[^>]+>|\s+)([^\s<]+)/g,
(match) => {
const color = colors[Math.floor(Math.random()*colors.length)];
return ` <span style="color: ${color}">${match}</span>`
}
);
<p>
some words some words
some words some words
some words some words
</p>