0

I would like to have the page scroll into an element with class xxxx when any element with class yyyy is clicked. I wrote this down but it does not work. Any help? I am sure I am doing something wrong but I don't know what.

var my_event = document.getElementsByClassName('yyyy');
my_event.onclick = function zb_scroll_function() {
const activity = document.getElementsByClassName('xxxx');
activity.scrollIntoView();};

On a site that I have no access over the DOM layout, I want to scroll to another area of the site when a link with a specific class is clicked.

1 Answers1

1

Getting elements by class name by getElementsByClassName you receiving HTMLCollection of elements, no single element.

but scrollIntoView is defined on single element, not a collection.

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

You can try:

const activity = document.querySelector('.xxxx');

To better understand context you should read also:

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

and

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

Daniel
  • 7,684
  • 7
  • 52
  • 76