HTML/jQuery – How do I dynamically highlight the current page or section?

What do I want?
jQuery to dynamically highlight the current page from the navigation bar.

Am I new to jQuery/HTML? Yes – apologies if it’s a silly question

Have I spent hours scouring existing StackOverflow posts to no avail? YES! These have been the most promising but for reasons I don’t understand, their suggestions aren’t working

What’s the problem?
Using the code below, I am trying to make the current page(/selected section) in my navigation bar stay highlighted in green (to show the end-user what page they’re currently on).

The hover-over functionality is working but I can’t seem to get it to stay that colour once I’ve clicked on it.

FYI – I’ve used #links and links.html in my "navigation menu" as I want the solution to work for both cases (although in the real thing I’ll have two separate menus: one with links to .html pages and one with links to #sections of the page.

Have I made a small reproducible example? See below

index.html:

<!DOCTYPE html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <link rel="stylesheet" href="test_main.css">
    
</head>

<body>

    <div class="navigation">
        <a href="test.html">Home</a>
        <a href="#section_a">Section A</a>
        <a href="#section_b">Section B</a>  
      </div>

      <script>
          $(function(){
              $('a').each(function(){
                  if ($(this).prop('href') == window.location.href) {
                      $(this).addClass('active'); $(this).parents('li').addClass('active');
                  }
              });
          });
      </script>
            
    <p>Example text</p>

</body>


main.css:


/* Add a white background color to the top navigation */
.navigation {
  background-color: #555555;
  color: #ffffff;
  overflow: hidden;
}

/* Style the links inside the navigation bar */
.navigation a {
  float: left;
  background-color: #555555;
  color: #ffffff;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Change the color of links on hover */
.navigation a:hover {
  background-color: #000000;
  color: #ffffff;
}

.active {
  background-color: #00ff00;
  color: #00000
}

I know this can be done statically by just setting class="active" in the navigation class but this is too cumbersome and not maintainable.