I am writing a JavaScript code where some characters of the string have a color and I want to display them through the HTML elements. I only want the ‘abc’ to be blue and no color change with ‘def’.
For example, if there’s a variable:
word = '<span style="color: blue">abc</span>def'
I used this to display the text in the HTML element:
presentCell.innerHTML = word;
Is there a way to not use .innerHTML
and do the same thing? I’m worried about security problems because I am getting user input for ‘abc’ and ‘def’.
I am making this word
variable with this function:
function changeTextColorArr (textArr, colorArr){
resultArr = [];
for(let i = 0; i < textArr.length; i++)
{
color = colorArr[i] === "" ? "black" : colorArr[i];
beginTag = `<span style="color: ${color}">`
endTag= '</span>';
result = beginTag + textArr[i] + endTag;
resultArr.push(result);
}
return resultArr;
}
//I get an array of an text and an array of colors correspoding to each text
let word = changeTextColorArr(["abc"], ["blue"]) + "def";
console.log(word)