skip to Main Content

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)

#UPDATE 2

function changeTextColorArr(textArr, colorArr) {
  resultArr = [];
  for (let i = 0; i < textArr.length; i++) {
      const span = document.createElement('span');
      const color = colorArr[i] === "" ? "black" : colorArr[i];

      span.style.color = color;
      span.textContent = textArr[i]; // Safely set the text content

      // push HTML code in a string format
      console.log( span.outerHTML);
      resultArr.push(span.outerHTML);
  }

  return resultArr;
}

2

Answers


  1. You could do something like

    presentCell.innerHTML = '';
    presentCell.appendChild(document.createTextNode(word));
    
    Login or Signup to reply.
  2. Avoid Using .innerHTML: Instead, create and append individual elements (e.g., ) directly to the DOM.

    Use document.createTextNode: This ensures that text content is inserted safely without any unintended HTML rendering.

    Use document.createElement: Create HTML elements like programmatically.

    function changeTextColorArr(textArr, colorArr) {
    const fragment = document.createDocumentFragment(); // Create a document fragment to avoid multiple reflows
    
    for (let i = 0; i < textArr.length; i++) {
        const span = document.createElement('span');
        const color = colorArr[i] === "" ? "black" : colorArr[i];
    
        span.style.color = color;
        span.textContent = textArr[i]; // Safely set the text content
    
        fragment.appendChild(span); // Append the span to the document fragment
    }
    
    return fragment;}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search