Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

74
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!

7 months 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!

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.