0

I have got a working table that when the button is pushed, a table is dynamically created by looping through an array and displaying that data in each cell.

However the problem arises when I am trying to add a table header for my table, and I'm not sure what I am doing wrong.

Here is my current working code: (although doesn't seem to work in JSFiddle?!)

And here is the code I am trying to add: (which must be wrong)

var thd=document.createElement("thead");
tab.appendChild(thd);

var tr= document.createElement("tr"); 
tbdy.appendChild(tr); 

var th= document.createElement("th");
th.appendChild(document.createTextNode("Name");
tr.appendChild(th);

Any help would be greatly appreciated,

4
  • 1
    You need to set the jsfiddle to not wrap the code in an onload event. jsfiddle.net/ahEkH/1 Commented May 31, 2014 at 21:42
  • You forgot to "close" the input, that's why the jsFiddle is not working: jsfiddle.net/ahEkH/3 Commented May 31, 2014 at 21:46
  • And the header works as well as long as you fix the missing ) in the second to last line. jsfiddle.net/ahEkH/2. Time to learn how the JavaScript error console works. Commented May 31, 2014 at 21:46
  • Instead of tbdy.appendChild(tr); you probably wanted to write thd.appendChild(tr);, no? Commented May 31, 2014 at 21:53

1 Answer 1

0

You can use a loop to avoid duplicating code. For example:

var columns = ["Name", "Age", "Degree"];

var thd = document.createElement("thead");
tab.appendChild(thd);

var tr = document.createElement("tr"); 
thd.appendChild(tr);

for (var i = 0; i < columns.length; i++) {
    var th = document.createElement("th");
    th.appendChild(document.createTextNode(columns[i]));
    tr.appendChild(th);    
}

Demo: http://jsfiddle.net/ahEkH/6/

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.