Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

350
Visualizações
How can I use innerText instead of innerHTML in dynamically created HTML elements?

I use Javascript to dynamically create a lot of elements. Divs, images, spans, etc.

Here is an example piece of code that my JS would run:

infoCell.innerHTML = "Submitted by " + "<a href='/user/" + this.poster + "'><img src='" + this.poster_avatar_src + "' class='avatarimg'>  <span style='color:blue'>" + this.poster + "</span> </a>in " + "<span style='color:blue; font-weight: 900;'><a href='/h/" + href + "'>" + this.topic + "</a></span>"

This was written early in my JS development, but now I realize that it can very quickly become very insecure, as almost all of the javascript variables being inserted into the HTML are written by the user with no limitations to character usage, etc.

How can I go through my javascript and change all of these so they still function, but without worrying about users inserting script into my site?

I am fine rewriting a lot but I would like to not do this again. I have about 90 innerHTML DOM modifications in my main JS file (typescript).

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you could try to use a combination of document.createElement and HTMLElement.append

an example for the first <a> tag:

function makeElem (tagname, properties) {
    let elem = document.createElement(tagname);
    for (const key in properties) {
        elem[key] = properties[key];
    }
    return elem;
}
infoCell.append("Submitted by ");
let a = makeElem("a", {href:'/user/"' + this.poster + '"'});
a.replaceChildren(makeElem("img", {'src':this.poster_avatar_src, 'className':'avatarimg'}), makeElem("span", {'textContent':this.poster,'style':'color:blue;'}));
infoCell.append(a);

this might not be the easiest but it should work, the reason for the "makeElem" function is purely convenience and you don't necessarily need it

about 4 years ago · Juan Pablo Isaza Relatório

0

There are a few approaches.

One is to use a sanitizer to translate all of the dynamic values into properly escaped strings before interpolation - but you'd have to be sure you get it right, otherwise there could still be problems.

Another way is to construct the element structure, then insert the dynamic strings at the appropriate points, eg:

const cell = document.createElement('div');
cell.innerHTML = `
  Person info
  <div class="name"></div>
  <div class="age"></div>
`;
cell.querySelector('.name').textContent = name; // where name is dynamic
cell.querySelector('.age').textContent = age; // where age is dynamic

But this can be tedious if you have a lot of dynamic values to insert.

A third way (and one that I'd recommend for serious applications) is to use a framework to handle it for you. For example, in React, the above "cell" could be made like:

const Cell = ({ name, age }) => (
  <div>
    Person info
    <div class="name">{name}</div>
    <div class="age">{age}</div>
  </div>
);

It takes some learning and getting used to, but once you get going it's a lot easier to read and write than other approaches.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda