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

227
Visualizações
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 Respostas
Responde à pergunta

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