How to Toggle Between Page Sections

I have a navigation bar where the tab gets highlighted if it’s clicked on. I also want it to highlight the section of the page I’m on. The HTML for the page section looks like this:

<section id="section1" data-nav="Section 1" class="active">
<div class="landing__container">
<h2>Section 1</h2>
<p>Lorem ipsum </p>
</div>
</section>

Here is the javascript I’m using. It works to highlight the tab that I’m on but it doesn’t highlight the section.

var tabs = document.getElementsByTagName("li");

for (var i = 0; i < tabs.length; i++) {
tabs[i].addEventListener("click", function() {
var element = document.getElementsByTagName("section");
element.classList.toggle('active');
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace("active", "");
this.className += "active";
});
}

var element = document.getElementsByTagName("section");

This returns a collection, not a single element, so you can’t use className on it.

When I add the following it doesn’t add the class. Doesn’t matter where in the code I am, it just doesn’t do it.

var section2 = document.getElementById(“section2”);
section2.classList.add(“active”);

My css was wrong. It’s working now.

It’s working now. I used the following:


var listelement1 = document.createElement('li');
listelement1.innerHTML = "TAB 1";
var section1 = document.getElementById("section1");

listelement1.addEventListener("click", function(){
document.location.href = '#section1';
section1.classList.add("my-active");
});