Home › Forums › JavaScript › [Solved] Remove empty class="" from DOM?
- This topic is empty.
-
AuthorPosts
-
October 11, 2013 at 8:15 pm #152791RuggParticipant
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 emptyclass= ""
— 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 #152794__ParticipantThere 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 #152807__ParticipantRight—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 ashidden=true
orhidden=false
; it is always “hidden” unless the attribute is actually removed). Butclass
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 #265667anduParticipantI’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-textJanuary 18, 2018 at 6:44 pm #265692ShikkedielParticipantOr just this:
$('#a').removeAttr('class');
February 26, 2018 at 4:47 pm #267522 -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.