It is impossible to apply a class to its element 'td'
re-assigning innerHTML
, whereas it is only the HTML interior of you. outerHTML
that would be correct, therefore it would be laborious and problematic to the interior elements.
It is easier to use browser methods that allow you to manipulate classes of an element easily.
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
(that is a Setter).
- Getting the interface
ClassList
on the property classList
, calling his methods add
, remove
, etc..
In my opinion it does not make much difference to re-assign className
in an element that may contain up to the maximum one class, but it would be better to use the methods of ClassList()
when modifying an element containing several classes, so you will not lose them.
It is not good to re-assign className
when an element may have dynamic classes, but it is still possible to keep classes with it, but in a more different way.
So 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>
To downvoters: on behalf of the community, it is right to comment on ways to improve the issue.
– vinibrsl
Claudia, could you clarify what you mean by class? Do you want to change the
td
and include a classCSS
? Or are you wanting to keep the<b>
?– Anthony Accioly
Why don’t you use
innerText
to exchange text, ifinnerHTML
can replace all contents.– KingRider
Anthony, I wanted to keep only the bold, I was testing and solved my problem by putting the "id" in the "<b>". Thank you!! : )
– Claudia Leandro
Just a hint: To assign a data value to an element, instead of using the insecure method, such as element.innerHTML = data, prefer a more secure option such as: element.textContent = data. So you are not vulnerable to cross-site scripting attacks (XSS).
– Giuliana Bezerra