19

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!

Glo
  • 604
  • 1
  • 4
  • 18
  • 2
    Perhaps it would be useful to tell us *why* you are trying to remove the attribute? – cdeszaq Jan 13 '10 at 15:52
  • Cdeszaq is right, the question is worded in such a way as to make us wonder if there is a better way to approach the problem. Without knowing the problem, we can't answer that. – Peter J Jan 13 '10 at 15:56
  • 1
    Added the whole script for your reference, thanks! – Glo Jan 13 '10 at 16:06

7 Answers7

21
$('*[class=""]').removeAttr('class');
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
6

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.)

CurtainDog
  • 3,175
  • 21
  • 17
1

After the document has been parsed and the DOM tree has been created, the element's attributes are really just properties of the individual DOM objects, so while you could remove the attribute from the source, it will still be present (but empty) on each object in the DOM.

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
  • 1
    Yea, you've made me realise that the extra jquery is kind of pointless, the extra miliseconds added to the pageload isn't worth it to remove the attribute really. Oh well, sorry for the pointless question in the end :S – Glo Jan 13 '10 at 16:25
1
$('li[class=""]').each(function() {
    this.removeAttribute('class');
});
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
0

You don't really need any libraries (like jQuery) do to this:

if (element.className == "")
    element.removeAttribute('class');
Iain Collins
  • 6,774
  • 3
  • 43
  • 43
0

Adding/removing classes is a core function of the jQuery library: http://docs.jquery.com/Attributes

You can see if any given collection of elements has the class in question with hasClass (http://docs.jquery.com/Attributes/hasClass#class)

And then remove a specific class with removeClass (http://docs.jquery.com/Attributes/removeClass#class)

So, if you need to remove class "abc" from a specific element do:

$("#element").removeClass("abc");

This will remove ONLY the indicated class, even if there are others in there. Adding a class works in the same way.

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
  • It's the class attribute I wanted to remove, not just a class and only if there are no classes. – Glo Jan 13 '10 at 16:13
  • But why? An empty class attribute doesn't do anything one way or the other. – cdeszaq Jan 13 '10 at 16:16
  • 1
    Cleaner html I guess, I suppose it doesn't really matter but at least I know for future reference! – Glo Jan 13 '10 at 16:19
  • But the HTML is only used to parse out the DOM tree. After than, the HTML is not edited by javascript, only the DOM tree itself. If it DID edit the HTML, the DOM would have to be re-parsed, and that would cause a major slowdown. Since having an empty class attribute doesn't hurt anything, I would not recommend removing it unless you have a massive page that needs the additional memory for other things because the time it takes to remove the attribute will make your page slightly slower for your users and give no real benefit. – cdeszaq Jan 13 '10 at 16:22
  • Yea, I'll probably just end up leaving the attributes in, cheers for the explanation. – Glo Jan 13 '10 at 16:45
0

Takes into account empty spaces within the class attribute:

var nodesWithClass = document.querySelectorAll("[class]");

[...nodesWithClass].forEach(node => {
  if( !node.className.trim() )
    node.removeAttribute('class');
})


console.log( document.body.children );
<a class="">one</a>
<a class=' '>two</a>
<a class='    '>three</a>

Of course this is a very generalized scenario and some things should be taken into account, such as the use of the querySelectorAll, which should be more specific probably, then searching the whole document for nodes with classes. Second is the transformation of the nodesWithClass HTMLCollection into an Array by using an ES2015 trick (see this question).

vsync
  • 118,978
  • 58
  • 307
  • 400