2

I have written a javascript code to dynamically generate a table ,How can I add class attribute to genrated table?

I have tried using addClass(), and .className. But it did't work for me.

Here is my code :

var res = data.split("\n");
rows = res.length; 
var body = document.getElementById(name);
tbl  = document.createElement('table');
tbl.style.width  = '100px';
tbl.style.border = "1px solid black";

//tb1.class("table"); tb1.className="table" tn.addClass() ="table"          

for(var i = 1; i < rows; i++)
{
        var tr = tbl.insertRow();
        var column = res[i].split("@"); 

        cols = column.length;

        for(var j = 0; j < cols; j++)
        {
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(column[j]));
            td.style.border = "1px solid black";
        }
        }
        body.appendChild(tbl);
}
2
  • I have written a jquery code There is no jQuery there Commented Jan 11, 2015 at 12:19
  • 1
    I think your problem is your name is wrong -> 'tb1' instead 'tbl' // tbl.className = 'table'; should work. Commented Jan 11, 2015 at 12:21

1 Answer 1

1

Try to use setAttribute

tbl.setAttribute('class', 'table')

Or you can use .classList

const app = document.getElementById('app');

document.getElementById('button').addEventListener('click', () => {
   const tbl = document.createElement('table');
   tbl.classList.add('class')
   app.appendChild(tbl)
})
.class {
   border: 1px solid red;
   height: 100px;
   width: 100px;
}
<div id="app"></div>
<button id="button">Add</button>

Sign up to request clarification or add additional context in comments.

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.