mohamed faiz mohamed faiz -4 years ago 112
ASP.NET (C#) Question

How to add css class to particular link in a group of links?

I have 5 links, I want to add

active
class to particular link.

For example

<div class="w3-sidebar w3-bar-block w3-collapse w3-card-2 w3-animate-left" style="width: 200px; padding-top: 50px;" id="mySidebar">
<button type="button" class="w3-bar-item w3-button w3-large w3-hide-large" onclick="w3_close()">Close &times;</button>
<a href="#" class="w3-bar-item w3-button">Create User</a>
<a href="#" class="w3-bar-item w3-button">Security</a>
<a href="#" class="w3-bar-item w3-button">Link 3</a>
<a href="#" class="w3-bar-item w3-button">Link 4</a>
<a href="#" class="w3-bar-item w3-button">Link 5</a>
</div>



If I want to add
active
class to second link(Security). How can I add.


$(document).ready(function () {

//ADD Active in SideNav bar
$('.w3-sidebar a').click(function (e) {
e.preventDefault();
$('.w3-sidebar a').removeClass('active');
$(this).addClass('active');
})
});


I tried the above code. But the problem is. When page get reload. That active is not appearing.

Answer Source

You have to select the 2nd element with your jquery and apply the active class every time on page load.

$(document).ready(function() {
  $(".w3-button:eq(2)").addClass("active");
  $('.w3-sidebar a').click(function(e) {
    e.preventDefault();
    $('.w3-sidebar a').removeClass('active');
    $(this).addClass('active');
  });
});
.active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="w3-sidebar w3-bar-block w3-collapse w3-card-2 w3-animate-left" style="width: 200px; padding-top: 50px;" id="mySidebar">
  <button type="button" class="w3-bar-item w3-button w3-large w3-hide-large" onclick="w3_close()">Close &times;</button>
  <a href="#" class="w3-bar-item w3-button">Create User</a>
  <a href="#" class="w3-bar-item w3-button">Security</a>
  <a href="#" class="w3-bar-item w3-button">Link 3</a>
  <a href="#" class="w3-bar-item w3-button">Link 4</a>
  <a href="#" class="w3-bar-item w3-button">Link 5</a>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download