Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Javascript jquery add active class

I'm trying to add active class to my unordered list using jQuery. I've tried many solutions on Stackoverflow and it doesn't seem to work. I want to make the active class color red. Can someone tell me why it is not working?

$("li").click(function() {
  $("li").removeClass("active");
  $(this).addClass("active");
});
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="navbar">
  <li class="active"><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
</ul>

I'm also getting this error in my browser console:

 error: $("li").click() is not a valid function
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your code works well. But I see that you said you are getting an error message error: $("li").click(function() is not a valid function. We usually get this error message when load our custom JS code that contains jQuery functions before loading the main jQuery script to the document

So to solve it put the jQuery library code inside the HTML <head></head> tag

.active { color: red; }
.active a { color: red; }
<!doctype html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
    <ul class="navbar">
      <li class="active"><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
    </ul>

    <!-- Your custom script here -->
    <script>
      $("li").click(function() {
        $("li").removeClass("active");
        $(this).addClass("active");
      });
    </script>
  </body>
</html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!