Barak Gzlee
Barak Gzlee

Reputation: 98

jquery's .removeclass removes the class but not the class attribute

basiclly i add and remove classes to certian elements but i need them to return to their original state after removal example:

before adding:

<a style="....">

after adding:

<a style="...." class="myclass">

after using .removeClass:

<a style="...." class="">

i want to get rid of that empty class tag

$("#example").addClass("removethis")
$("#example").removeClass("removethis")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="example">this is the example tag inspect me</a>

after running the snipper if we look at the "a" tag we see this

<a id="example" class="">this is the example tag inspect me</a>

how would i remove that empty tag

Upvotes: 1

Views: 829

Answers (3)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

You can check for empty class and remove the attribute while using removeClass like,

$("#example").removeClass("removethis").filter('[class=""]').removeAttr('class');

And the snippet as follows,

$("#example").addClass("removethis")
$("#example").removeClass("removethis").filter('[class=""]').removeAttr('class');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="example">this is the example tag inspect me</a>

Upvotes: 2

Mihail Minkov
Mihail Minkov

Reputation: 2633

You could use the removeAttr("class") function jQuery also offers.

The example would be something like:

$("#example").removeAttr("class");

The only problem here is that if the element has other classes they would all be removed.

If you were to verify if the element has other classes you could do this:

var classes = $("#example").attr("class").trim();
var classesArray = classes.split(" ");

if(classesArray.length == 0) {
   $("#example").removeAttr("class");
} 

This could be done in fewer lines, but I am making it explicit in order to make it clearer.

The first line would result in a string containing all classes that's previously trimmed just in case to avoid white spaces.

The second line converts that string in an array of string elements using the space as separator. It might not be perfect, depending on what you use case is.

If you check the length of that array and it's zero that means you have no classes and you can remove the attribute.

Upvotes: 2

Taplar
Taplar

Reputation: 24965

Ok, so ignoring the use case for this and just focusing on the ability to do so, this could be done like the following.

var $example = $("#example").addClass("removethis");
$example.removeClass("removethis");

if (!$example.prop('classList').length) $example.removeAttr('class');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="example">this is the example tag inspect me</a>

You can check the length of the classList property and if it is empty, remove the attribute entirely.

Upvotes: 2

Related Questions