javascripthtmldomexception

Why is there an error saying Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#1' is not a valid selector


When I click the "Open Account" button on the navigation I get the error:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#' is not a valid selector.

// Page Navigation
document.querySelector('.nav__links').addEventListener('click', function (e){
  // Matching element
  e.preventDefault();
  if (e.target.classList.contains('nav__link')) {
        const id = e.target.getAttribute('href');
        document.querySelector(id).scrollIntoView({behavior: 'smooth'});
  }
});


document.querySelector(id).scrollIntoView({behavior: 'smooth'});

...and here is the button HTML:

<li class="nav__item">
  <a class="nav__link nav__link--btn btn--show-modal" href="#">Open account</a>
</li>

Not sure what I'm missing to get rid of the error.


Solution

  • The event listener requires the href in the navigation link to be a valid selector for the element to scroll to. So change

    <a class="nav__link nav__link--btn btn--show-modal" href="#">Open account</a>
    

    to

    <a class="nav__link nav__link--btn btn--show-modal" href="#someid">Open account</a>
    

    and replace someid with the ID of the element that contains the account opening form that you want to scroll to.