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

235
Vistas
Javascript dies when a div with getElementsByClassName is not found. How can I improve this?

I am writing a script for a Shopify theme app extension intended to look for a specific div on the page and replace it with my content. However, with all the various themes available on Shopify, the way developers label this div is not consistent. I would like to compile every possible combination and have it ready in the app to find this particular div and inject my content. I started simply with this...

document.getElementsByClassName('my__div')[0].innerHTML = 'new content';
document.getElementsByClassName('my--div')[0].innerHTML = 'new content';

When testing, any theme with 'my__div' worked. Any theme with 'my--div' did not.

I flip-flopped the lines of the code and saw that I got the reverse effect.

What causes the second line to fail when the first line cannot be executed? And is there an if statement I can use to make it work for all scenarios?

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Teemu directed me to this solution. I thought I would post the working code to help future visitors...

var x = document.querySelectorAll(".my--div, .my__div");
var i;
for (i=0; i < x.length; i++) {
    x[i].innerHTML = 'new content';
}

Now I can add variation I find into the first line and it will still work on any theme the app loads onto.

Cheers!

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