How to move to a Div tag with any ID with JavaScript

Tram Ho

Sometimes, we want to jump to an element with any ID using JavaScript.

In this article, I will show you how to scroll to any element using JavaScript.

Use location.href and history.replaceState

We can use the location.href attribute to get the URL and omit the hashtag # part. For example: https://itzone/u/Clarence161095#fullname then location.href will drop #fullname and just get https://itzone/u/Clarence161095 .

We can then append an arbitrary hashtag # to it.

For example, we have the following HTML code:

Then we can add a button to scroll down div with the ID of b on click:

We have a jump function with the h parameter being the ID of the element we want to scroll to.

Next, we get the current URL with location.href .

Then we add hashtag # with ID h to it to jump to the element with ID h .

And then we call history.replaceState with url as the 3rd argument to replace the URL with hashtag # with the original URL.

Next, we use document.querySelector to get the part from button .

And then we call addEventListener with the 'click' event to add the click listener .

The 2nd argument is a callback function that calls jump and passes 'b' to scroll to div with ID b .

Summary

We can use the location.href attribute to get the URL without hashtag # .

Then we append hashtag # to it.

And then we can remove hashtag # from the URL in the URL bar using history.replaceState .

Roundup

As always, I hope you enjoyed this article and learned something new.

Thank you and see you in the next posts!

If you find this blog interesting, please give me a like and subscribe to support me. Thank you.

Ref

Share the news now

Source : Viblo