1

I want to create buttons and add classes to those button after creation I am working on below code !1 Please Help me out :)

Will this work?

$("#"+element.id).addClass(".btn");

Thank you in advance !!

for (var i = 0; i < 9; i++) {
  add(i);
}

function add(i) {

  var element = document.createElement("input");

  element.type = "button";
  element.value = i;
  element.name = i + 1;
  element.id = "btn" + i;
  element.onclick = function() {
    window.move(i);
  };

  var append = document.getElementById("append");

  append.appendChild(element);
  alert(element.id);
  $("#" + element.id).addClass(".btn");
}

2
  • Possible duplicate of How do I add a class to a given element? Commented Nov 22, 2017 at 8:35
  • when using .addClass() you can omit the . in front of the classname Commented Nov 22, 2017 at 8:35

5 Answers 5

4

You can add classes in javascript like that:

element.className += 'className';

If you are using jQuery then what you did is correct, except the dot you put into addClass function. So instead of:

$(element).addClass('.className');

You do:

$(element).addClass('className');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, It Worked :)
2

You can add class directly by accessing "className" property.

var element = document.createElement("input");

element.type = "button";
element.className = "clr-red";

Refer here for more

Comments

2

I think you should use without dot.

$("#"+element.id).addClass("btn");

Comments

2

You can just use the classList.add method on the element you create.

   for (var i = 0; i < 9; i++)
    {
        add(i);
    }
    function add(i) {

        var element = document.createElement("input");

        element.type = "button";
        element.value = i; 
        element.name = i + 1;
        element.id="btn"+i;
        element.classList.add("btn");
        element.onclick = function () { 
            window.move(i);




        };


        var append =document.getElementById("append");
        append.appendChild(element);

    }

Comments

1

you just type the class name only

addClass("btn"); instead of addClass(".btn");

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.