tuscan88
tuscan88

Reputation: 5829

className is not a function

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

Answers (2)

Rajesh
Rajesh

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:

  • Add
  • Remove
  • Toggle

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

KevBot
KevBot

Reputation: 18888

className is a getter/setter. It should be used like this:

theAlert.className = 'alert alert-danger';

Upvotes: 14

Related Questions