Reputation: 5829
When I run the following code:
theAlert = document.createElement("div");
theAlert.className('alert alert-danger');
I get this error:
theAlert.className is not a function
What is wrong how come this doesn't work?
Upvotes: 3
Views: 8074
Reputation: 24915
As an alternate to @KevBot's answer, you can also use element.classList
Element.classList also provide APIs that comes handy and are declarative:
Sample:
document.getElementById('btnAdd').addEventListener('click', function(){
document.querySelector('.content').classList.add('color')
})
document.getElementById('btnRemove').addEventListener('click', function(){
document.querySelector('.content').classList.remove('color')
})
document.getElementById('btnToggle').addEventListener('click', function(){
document.querySelector('.content').classList.toggle('color')
})
.color{
background: #333;
color: #ddd;
}
<div class='content'>Test</div>
<button id="btnAdd">Add</button>
<button id="btnRemove">Remomve</button>
<button id="btnToggle">Toggle</button>
Upvotes: 5