Pedro Corchero Murga
Pedro Corchero Murga

Reputation: 505

Avoid adding attribute class empty if the condition is false

I have a few conditions of links: If the location of href is x, the function add a class with name "marked". The problem of that the function is adding me empty class to the other false conditions, so I want to delete the empty class on the false condition. Example:

True condition:

<li class="nav-item "><a href="/biblioteca/buzon-sugerencias" class="marked">Buzón de sugerencias</a> </li>

False condition:

<li class="nav-item "><a href="/biblioteca/authors" class="">Autores</a></li>

JQuery script of the function:

$(document).ready(function() {
    if(window.location.href.match('residenciarucab.es/biblioteca/books')){
        $(".nav-item:nth-child(1) a").addClass("marked");
    }
    if(window.location.href.match('residenciarucab.es/biblioteca/authors')){
        $(".nav-item:nth-child(2) a").addClass("marked");
    }
    if(window.location.href.match('residenciarucab.es/biblioteca/buzon-sugerencias')){
        $(".nav-item:nth-child(3) a").addClass("marked");
    }
    if(window.location.href.match('residenciarucab.es/biblioteca/desiderata')){
        $(".nav-item:nth-child(4) a").addClass("marked");
    }
        if(window.location.href.match('residenciarucab.es/biblioteca/book')){
        $(".nav-item:nth-child(1) a").addClass("marked");
    }
});

Upvotes: 0

Views: 29

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can use removeAttribute to remove class attribute as

document.querySelector('.nav-item:nth-child(1) a').removeAttribute("class");

or in jquery removeAttr use

$('.nav-item:nth-child(1) a').removeAttr('class');

//document.querySelector('.nav-item:nth-child(1) a').removeAttribute("class");
$('.nav-item:nth-child(1) a').removeAttr('class');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="nav-item "><a href="/biblioteca/authors" class="">Autores</a></li>
</ul>

Upvotes: 1

Related Questions