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