0

I have a few buttons that were made though a loop in javasript.

    var docFrag = document.createDocumentFragment();
    for (var i=0; i < 9 ; i++){ 
        var row = document.createElement("tr") 
        for (var j=0; j < 9 ; j++){ 
                var elem = document.createElement('input');
                elem.class = 'gumb';
                elem.style.color = 'purple';
                elem.type = 'button';
                elem.id = 'r'+i+'s'+j;
                elem.value = '';
                elem.innerHTML = elem.value; 
                docFrag.appendChild(elem); 
            } 
        document.body.appendChild(docFrag); 
        document.body.appendChild(row); 
    } 

And I want to apply css to them, but nothing seems to work. I tried it using elem.style and through a special style.css file using the button's class but it doesn't work and I don't know why.

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
Snowwy
  • 40
  • 4

3 Answers3

4

Usage of elem.class is wrong. Following usages are valid:

  • elem.classList.add('gumb')
  • elem.className = 'gumb'
  • elem.setAttribute('class', 'gumb')
Parnab Sanyal
  • 749
  • 5
  • 19
3

You need to change elem.class to elem.className

https://www.w3schools.com/jsref/prop_html_classname.asp

class is a reserved word in a lot of languages, so you'll find it might have an alternative name, such as className

andy mccullough
  • 9,070
  • 6
  • 32
  • 55
1

You need use elem.className = 'gumb'; also should set value for button to have purple color

   var docFrag = document.createDocumentFragment();
    for (var i=0; i < 9 ; i++){ 
        var row = document.createElement("tr") 
        for (var j=0; j < 9 ; j++){ 
                var elem = document.createElement('input');
                elem.className = 'gumb';
                
                elem.style.color = 'purple';
                elem.type = 'button';
                elem.id = 'r'+i+'s'+j;
                elem.value = 'A';
                elem.innerHTML = elem.value; 
                docFrag.appendChild(elem); 
            } 
        document.body.appendChild(docFrag); 
        document.body.appendChild(row); 
    } 
.gumb{
background-color:"#fff";
}
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62