I am making a shop, and I made a “Colors available” part, but I want to be able to color separate words with different colors, in Javascript, css, or HTML, or however it is possible
JavaScript
x
13
13
1
<button onclick="getColors()">Colors Available</button>
2
<script>
3
4
function getColors(){
5
if(!document.getElementById('colors_ava')){
6
let colors_ava = document.createElement('div');
7
colors_ava.id = 'colors_ava';
8
document.body.appendChild(colors_ava);
9
colors_ava.innerText = "Rich Navy - True Red - Dark Geen - Olive Drab Green - Patriot Blue";
10
}
11
}
12
</script>
13
Advertisement
Answer
You can have util method to create span with style.
JavaScript
1
17
17
1
function getColors() {
2
function createSpan(str, color) {
3
const span = document.createElement("span");
4
span.style.color = color;
5
span.style.marginRight = "20px";
6
span.textContent = str;
7
return span;
8
}
9
if (!document.getElementById("colors_ava")) {
10
let colors_ava = document.createElement("div");
11
colors_ava.id = "colors_ava";
12
document.body.appendChild(colors_ava);
13
colors_ava.append(createSpan("Red color - ", "red"));
14
colors_ava.append(createSpan("Blue color - ", "blue"));
15
// colors_ava.innerText = "Rich Navy - True Red - Dark Geen - Olive Drab Green - Patriot Blue";
16
}
17
}
JavaScript
1
1
1
<button onclick="getColors()">Colors Available</button>