Reputation: 2025
i am trying to create a to-do list in JavaScript where list is created dynamically on submitting inputs.What i want is list of task and a delete button besides them.All is done except that i am unable to add classes to button using javascript.
Here is my code..
<button id="add" onclick="takeInput()">Add new task</button>
<script>
function takeInput()
{
var task=prompt("Enter the new to do work");
if(task!=null)
{
var list=document.createElement("li");
var btn=document.createElement("button");
var data=document.createTextNode(person);
var btndata=document.createTextNode("delete");
list.appendChild(data);
btn.appendChild(btndata);
document.getElementById("list").appendChild(list);
document.getElementById("list").appendChild(btn);
}
}
</script>
Upvotes: 1
Views: 14506
Reputation: 21
You can use classList.Add
Here's a sample:
btn0.classList.add('btn');
btn0.classList.add('btn-sm');
btn0.classList.add('btn-primary');
Upvotes: 0
Reputation: 8488
You can add a class to your dynamically created button like this:
....
var btn=document.createElement("button");
btn.className = "YourClass";
//OR
btn.className += " YourClass" //If you want to add to existing classes
....
Upvotes: 9
Reputation: 7052
To add class to any html element you can use.
element.className += " newClass";
This will preserve previous classes and add new class.
In you case it would be like (if you want to add class to you newly created button)
btn.className += " newClass";
if you don't want the previous class.(in your case there is none)
btn.className = " newClass";
Upvotes: 2