2

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>

1 Answer 1

2

The element probably hasn't been loaded when you tried selecting it. Try selecting it only after all the elements have been loaded.

window.addEventListener('DOMContentLoaded', (event) => {
  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>

Sign up to request clarification or add additional context in comments.

1 Comment

This is the most probable reason. Another approach to tackle the same problem is to add the 'defer' attribute to the script tag that loads the JS file. This ensures that the JS runs after the DOM has been loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.