0

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");
}
empiric
  • 7,825
  • 7
  • 37
  • 48
Vaisakh MA
  • 94
  • 1
  • 1
  • 11
  • Possible duplicate of [How do I add a class to a given element?](https://stackoverflow.com/questions/507138/how-do-i-add-a-class-to-a-given-element) – Sean Nov 22 '17 at 08:35
  • when using `.addClass()` you can omit the `.` in front of the classname – empiric Nov 22 '17 at 08:35

5 Answers5

2

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');
Roland Ruul
  • 1,172
  • 8
  • 15
2

I think you should use without dot.

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

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

    }
MartinWebb
  • 1,998
  • 1
  • 13
  • 15
1

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

Anmol Mittal
  • 843
  • 5
  • 12
1

you just type the class name only

addClass("btn"); instead of addClass(".btn");
lee
  • 19
  • 2