Forums

Give help. Get help.

  • # October 11, 2013 at 8:15 pm

    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?

    __
    # October 11, 2013 at 9:24 pm

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

    __
    # October 12, 2013 at 12:48 am

    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?

    # January 17, 2018 at 11:30 pm

    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

    # January 18, 2018 at 6:44 pm

    Or just this:

    $('#a').removeAttr('class');
    
    # February 26, 2018 at 4:47 pm

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

You must be logged in to reply to this topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag