Reputation: 65
i created a django project : so in my page html , i have a list of words colorated with different background colors :
hello (colored in red)
world (colored in yellow)
i do this with :
<span class="token-label" style="background-color=red">hello</span>
in the same page , i want to display the text which contains the two words , but i want to colors the words in the text according to colors of each word:
hello, i'am here ! hello world ! with "hello" colored with red and "world" in yellow
Upvotes: 0
Views: 134
Reputation: 1159
I can't write a full idea of mine I think you can write it by yourself and here a quick example of what I wanted to create, it's not perfect because of its hardcoded regexp expression in .replace() method but I hope you will understand what I wanted to achieve
I would do it with regexp because I can have something like hello, (as in your example) or !world! and if you want to trigger those words you have to use regexp I hope so. You probably want to separete ! from "world" ! It will be something like
<span>!<span><span class="world">world<span><span>!</span>
CODE:
<p class="text">
hello, i'am here ! hello world !
</p>
.hello {
background-color: red;
}
let text = document.getElementsByClassName('text')[0].innerHTML;
let text_split = text.split(' ')
let new_arr = []
for(let i = 0; i < text_split.length; i++) {
new_arr.push(`<span class="${text_split[i].replace(',',
'')}">${text_split[i]}</span>`)
}
document.getElementsByClassName('text')[0].innerHTML = new_arr.join(' ');
https://jsfiddle.net/tj67q1zd/
Upvotes: 1