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

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

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