1

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>

3 Answers 3

9

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
....
Sign up to request clarification or add additional context in comments.

Comments

2

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";

Comments

0

You can use classList.Add Here's a sample:

btn0.classList.add('btn');
btn0.classList.add('btn-sm');
btn0.classList.add('btn-primary');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.