Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

347
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda