let combo = document.getElementById("string_determine");
let div = document.getElementById("mybox");
// I'm learning javascript. I would like to be able to add multiple colored text in my javascript. I would like the "This is black" text to be in black color and "This is blue" to be in blue color. As currently they both display as blue.
let string_determine;
switch(combo.options[combo.selectedIndex].text){
case '"blueblue"':
string_determine = "This is black" + "This is blue"; div.style.color = "blue"; break;
There is no need for switch statement. You can try surrounding the text with a span element with a style property of the color you want:
function setTextColor(element, text, color) {
const elementContent = element.innerHTML;
if (elementContent.search(text) !== -1) {
const coloredElement = `<span style="color: ${color}">${text}</span>`;
const newElementContent = elementContent.replace(text, coloredElement);
element.innerHTML = newElementContent;
} else {
console.error(`Cannot find text "${text}" in the given element`);
}
}
const combo = document.getElementById("string_determine");
// Text Element | Text to Stylize | Color (Any format of color supported in CSS)
// ----- ------------- -----
setTextColor(combo, "This is red", "red");
setTextColor(combo, "This is green", "#00ff00");
setTextColor(combo, "This is glue", "rgb(0, 0, 255)");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.