Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if the class attribute is empty and then removing it if true with jQuery

Tags:

jquery

I want to remove the class attribute from all elements that have an empty class attribute.

Eg:

`<li class="">One</li>`

becomes

<li>One</li>

I have been messing about for ages trying to work it out! The closest I got was

var len = $(".splitcolcontainer ul li[class]").val().length;
 if (len == 0)
  {
  $('.splitcolcontainer ul li').removeAttr("class");
  }

But no cigar. I know it's going to be desperately simple but no amount of Googling has show me the light! Cheers.

EDIT: As people have asked why I want to remove it, here is the whole script:

$(document).ready(function() {
     $( '.splitcolcontainer ol, .splitcolcontainer ul').each(function() {
          if($(this).is("ol")) { var ordered = true; }
          var colsize = Math.round($(this).find("li").size() / 2);
          $(this).find("li").each(function(i) {
               if (i>=colsize) {
                    $(this).addClass('right_col');
               }
            });
          if(ordered) {
               $(this).find('.right_col').insertAfter(this).wrapAll("<ol class='splitcol' start='" + (colsize+1) + "'></ol>").removeClass("right_col");

          } else {
                $(this).find('.right_col').insertAfter(this).wrapAll("<ul class='splitcol'></ul>").removeClass("right_col");            
            }

     });


    $('.splitcolcontainer').after('<div class="clear">&#160;</div>');
    $('.splitcolcontainer ul, .splitcolcontainer ol').wrap('<div></div>');
});

The reason there is an empty class is because I am adding the class 'right_col' and then removing it later on. I don't know whether there are going to be other classes or not so that's why I needed to check whether the attribute is empty. Thanks for the help so far!

like image 968
Glo Avatar asked Jan 13 '10 15:01

Glo


2 Answers

$('*[class=""]').removeAttr('class');
like image 125
David Hedlund Avatar answered Sep 28 '22 06:09

David Hedlund


I agree, it's very odd that removeClass leaves an empty class attribute hanging around. I would expect that after an addClass, removeClass would return the DOM to its original state.

What I've ended up doing is:

$(this).removeClass("my-class").filter('[class=""]').removeAttr('class');

which should be quite performant.

(My code is for an HTML editor, so it's important the code produced is as clean as possible.)

like image 28
CurtainDog Avatar answered Sep 28 '22 05:09

CurtainDog