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

156
Views
How do I stop JavaScript running on pages that do not contain elements in query?

I have some very simple JavaScript in a Joomla 4x development website to add a class to the first element it finds containing specific classes. It works perfectly on the page that contains those elements, but on any other page I get the message "Uncaught TypeError: Years is null". I'm using querySelector so that the script will stop at the first instance of the CSS class, which is what I want.

This is my code:

      if (document.querySelectorAll('.group-toggle')) {
      let Years = document.querySelector('.year.toggle-form');
      Years.classList.add('form-opened');
      }

I have tried the following:

function openYears() {
    if (document.querySelectorAll('.group-toggle')) {
    let Years = document.querySelector('.year.toggle-form');
    Years.classList.add('form-opened');
    }
}

and also

if (document.querySelector('.group-toggle')) {
let Years = document.querySelector('.year.toggle-form');
      function openYears(){
        let Years = document.querySelector('.year.toggle-form');
        if (document.querySelector('.group-toggle')) {
        Years.classList.add('form-opened');
        }
    }
}

but although the error message goes away, the script no longer works.

I'm sure it's blindingly obvious to you, but not to me.

TIA

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If there is no matching element, the result of querySelectorAll will be an empty array. An empty array is also truthy however (if ([]) alert('hi') will show the alert).

You could either check the array's length instead (if (document.querySelectorAll(...).length) - zero isn't truthy) or replace querySelectorAll with plain querySelector, because the latter looks for just the first matching element and returns it (not an array of elements), and it will return null (which is not truthy) if no such element could be found.

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!