Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!