I am trying to update a class when the user arrives on the web page. I am having trouble getting the script to work on my end. When a user arrives on the page and the link has a specific has, then I would like to update/add the href with a class of 'active', otherwise, I want to remove 'active' from the class if it is already present.
I tried the following script, I am getting the existing hash and if the hash is not null, then I want to make the change; the script is failing with an error: 'Cannot read property 'classList' of null'
const serv = document.getElementById('serv')
var hash = window.location.hash;
hash = hash.slice(1);
if (hash !== '') {
serv.classList.add('active');
} else {
serv.classList.remove('active');
}
<a id="serv" class="nav-link scrollto " href="~/#services">Services</a>