Edoras Edoras - 1 year ago 68
Javascript Question

AddClass "active" where Class is same as href, otherwise remove "active"

I'm doing probably something wrong, if I will click on

tag with class "sw" and
, I need remove class "active" from all
tags with class "sw", but also I need add "active" to all rest
tags with class which is same as href in
link, where I am clicking.

Thats mean, I need remove hash from href, because I am looking for that class not ID.

for example:

<a href="#m1" class="sw">CL1<a/>
<a href="#m2" class="sw active">CL2<a/>
<div class="sw m1>HELLO1</div>
<div class="sw m2 active>HELLO2</div>

if I will click on CL1, then I need remove all active from all sw divs and a, but also I need addclass "active" to all divs and a where is #m1 as class.

I hope u will underestand me :(

Here is my 2 testing codes ...

$('a.sw').on('click', function() {
var nohash = $(this).attr('href').replace('#', '');
if ( !$( this ).hasClass( "active" ) ) {
$('.sw').each(function() {
if($(this).hasClass('active')) {
} else {

$( 'a.sw' ).on( 'click', function() {
$('div.sw').removeClass( 'active' );
$(this).href().replace('#', '').addClass( 'active' )

Answer Source

Take moment and read Decoupling Your HTML, CSS, and JavaScript - Philip Walton @ Google

Based on your current code, you have a very high degree of coupling and virtually no reuse of your code. Here is how I would refactor it:


<a href="#m1" class="js-sw active" data-sw-target=".sw-target-m1">CL1</a>
<a href="#m2" class="js-sw" data-sw-target=".sw-target-m2">CL2</a>
<div class="sw-target sw-target-m1 active">HELLO1</div>
<div class="sw-target sw-target-m2">HELLO2</div>


$(document).ready(function() {
  $('.js-sw').on('click', function() {
    $('.sw-target, .js-sw').removeClass('active');

    var selector = $(this).data('sw-target');

Now the code works for anything marked as .js-sw. You can change the target selector to whatever you want including multiple selectors (ex. data-sw-target=".sw-target, .someothertarget").

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