How to scroll to an element without # in the URL with JavaScript?

Sometimes, we want to scroll to an element without # in the URL with JavaScript.

In this article, we’ll look at how to scroll to an element without # in the URL with JavaScript.

How to scroll to an element without # in the URL with JavaScript?

To scroll to an element without # in the URL with JavaScript, we can use the scrollIntoView method.

For instance, we write:

<p id='top'>top</p>

<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>

<button>
  scroll to top
</button>

to add some elements onto the page.

Then we write:

const button = document.querySelector('button')

button.addEventListener('click', () => {
  document.getElementById('top').scrollIntoView(true);
})

We select the button with document.querySelector.

Then we call button.addEventListener to add a click listener to the button.

In the click listener, we select the element with id top with document.getElementById.

Then we call scrollIntoView with true to scroll to the element we selected.

Now when we click on the button, we should scroll back to the top of the page.

Conclusion

To scroll to an element without # in the URL with JavaScript, we can use the scrollIntoView method.