Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript [Solved] Remove empty class="" from DOM?

  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #152791
    Rugg
    Participant

    Wondering if there’s a method for removing empty class strings from the DOM?

    For Example:

    Using jQuery .addClass('current'); to the current element in a set of divs will update the DOM tree accordingly. If, however, the element does not initially have a class name, the class string will remain empty class= "" — even after using .removeClass('current');.

    Before Traversing DOM Tree:

     <div id="a" class="current"></div>
     <div id="b"></div>
     <div id="c"></div>
     <div id="d"></div>
    

    After:

    <div id="a" class=""></div>
    <div id="b" class=""></div>
    <div id="c" class=""></div>
    <div id="d" class="current"></div>
    

    Can class="" be removed from the DOM? Or is this default behavior?

    #152794
    __
    Participant

    There is no difference between an empty class attribute and not having it there at all. The DOM looks the same either way.

    (Remember, the HTML markup is not the DOM. Neither is the markup you see in dev tools/ firebug/ whatever. It’s just a representation.)

    #152807
    __
    Participant

    Right—that’s just a representation of the DOM, not the DOM itself.

    I’m not sure if there is any effective difference between <element class=""> and <element>, but I’ve never come across any.

    Some elements are boolean (hidden, for example, is the same as hidden=true or hidden=false; it is always “hidden” unless the attribute is actually removed). But class doesn’t work that way.

    Is there some problem you actually need to solve, or are you just exploring the behavior?

    #265667
    andu
    Participant

    I’m aware this is a very old question, but having to deal with this issue myself, I thought about posting the answer. Maybe it will help others along the way:

    for the whole document:
    document.body.innerHTML = document.body.innerHTML.replace(/class=””/g, ”);

    for a specific element:
    myParent.innerHTML = myParent.innerHTML.replace(/class=””/g, ”);


    Inspired from:
    https://stackoverflow.com/questions/5558613/replace-words-in-the-body-text

    #265692
    Shikkediel
    Participant

    Or just this:

    $('#a').removeAttr('class');
    
    #267522
    nevf
    Participant

    @andu This will not only replace empty class attributes but also any class=”” text, which is not what one would want.

Viewing 6 posts - 1 through 6 (of 6 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.