It is impossible to apply a class to its element 'td'
re-assigning innerHTML
, which is only the inner HTML of itself. outerHTML
that would be correct, so it would be laborious and problematic to the interior elements.
It is easier to use browser methods that allow you to easily manipulate an element's classes.
So far, according to the answers in these questions, we have two ways of manipulating the classes of an element:
- Re-assigning the property
className
(which is a setter).
- Taking the interface
ClassList
on the classList
property, calling its methods add
, remove
, etc.
In my opinion it does not make much difference to re-assign className
to an element that can contain up to a class, but it would be better to use ClassList()
methods when modifying an element containing several classes, so you will not lose them.
It is not good to re-assign className
when an element can have dynamic classes, but it is still possible to maintain classes with it, but in a more different way.
Then re-assigning className
:
/* perdeu a classe 'ball' */
wow.className = "new-class";
/* agora só resta 1 bola, portanto 'wow' não foi removido */
.ball {
background-color: #f05;
border-radius: 100%;
width: 50px;
height: 50px;
}
<div class="ball"></div>
<div class="ball" id="wow"></div>
Using ClassList()
:
wow.classList.add("new-class");
/* ainda restam 2 bolas */
.ball {
background-color: #f05;
border-radius: 100%;
width: 50px;
height: 50px;
}
<div class="ball"></div>
<div class="ball" id="wow"></div>