0

I have question about how scrollIntoView is working, so why scrollIntoView working like this:

liItems.forEach(val => {
   val.addEventListener('click', e => {
   e.preventDefault(); 
   document.querySelector(val.getAttribute('href')).scrollIntoView({
     ...
   })
 })
})

But not working like this:

liItems.forEach(val => {
   val.addEventListener('click', e => {
   e.preventDefault(); 
   val.getAttribute('href').scrollIntoView({
    ...
   })
 })
})

1 Answers1

2

scrollIntoView is a method on Elements.

querySelector returns an Element. That's why the first example works:

const elem = document.querySelector(val.getAttribute('href')); // this is an Element
elem.scrollIntoView(); // OK!

getAttribute, however, is a method on Element which returns a string:

const someHref = val.getAttribute('href'); // this is a string
someHref.scrollIntoView(); // error :( strings don't have scrollIntoView
rsmeral
  • 518
  • 3
  • 8