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,449
  • 6
  • 35
  • 44
Vaisakh MA
  • 84
  • 1
  • 9
  • 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) – hammy2899 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

1

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,142
  • 8
  • 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
  • 823
  • 5
  • 12
1

I think you should use without dot.

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

1

you just type the class name only

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

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,748
  • 1
  • 11
  • 12