Scroll to the first markup with a certain text

Sometimes in long webpages we want to scroll down or up to a certain point in the webpage.

For example, a recipes website may have long webpages with a recipe webpage like with <h1>Original San Fransico Chinese-American Fortune Cookies</h1> and then much possibly “junk data for SEO” and only then something practical like <h2>Ingredients</h2> to which we want to scroll to.

How will you suggest to do this with vanilla JavaScript?


A starting point could be this:

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

But how to condition it by textContent?

I have found this to be a nice sloution:

headingText ="Ingredients";
document.querySelectorAll('h2').forEach( (element)=>{
    if (element.textContent == headingText) {
        element.scrollIntoView({
            behavior: 'smooth'
        });
    }
});
1 Like

It’s worth noting that you can do this with one simple line of CSS:

html {
  scroll-behavior: smooth;
}

1 Like