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:
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";
});
}
on a side/general note, i dislike the use of ‘active’ as a class name, as it’s already a selector in css. .active and :active are just too close for me…shrug
Back to the main point, you’ll need to walk the dom backwards from this in order to find the section that the click corresponds to.
that tries to turn on every other section, and turn off the current active section. Probably not what you’re trying to do.
Generally when doing something like this, the flow is:
Remove the tag from everything.
Add the tag to the required element(s).