1

I'm creating an HTML table using JavaScript:

function CreateArray(){
  var arr = [];
  for(var i = 0 ; i < 10; i++){    
    arr.push({
      firstName:"John",
      lastName:"Doe",
      email:"email"+i.toString()+"@gmail.com"
    }); 
  } 
  return arr;
}

function CreateTable(data) {   
  var tableStr = [];
  var j = -1;

  tableStr[++j] = '<table class="tftable" border="1"><thead><tr><th><input type="checkbox" id="allEmails" onclick = "SelectAllEmails()"/></th><th>First Name</th><th>Family Name</th><th>Email</th></tr></thead><tbody>';

  for (var i = 0; i < data.length; i++) {
    tableStr[++j] = '<tr><td>';
    tableStr[++j] = '<input type= "checkbox"';
    tableStr[++j] = 'id =' + "chbxEmail" + i.toString() +" "+'onclick =' + "foo(this)"+" "+'/>';
    tableStr[++j] = '</td><td>';
    tableStr[++j] =  data[i].firstName;
    tableStr[++j] = '</td><td>';
    tableStr[++j] = data[i].lastName;
    tableStr[++j] = '</td><td>';
    tableStr[++j] = data[i].email;
    tableStr[++j] = '</td></tr>';
  }
  tableStr[++j] = '</tbody></table>';
  var table = tableStr.join('');
} 

I need to get all rows inside the HTML table except the header row. I've tried it this way:

var trows =  table.getElementsByTagName('tbody')[0].rows;
alert(trows.length);

But I don't get any result. Even the alert box is not displayed.

How can I get the rows inside the table variable without the header row?

2
  • Where are called the code with alert ? Anyway is much better to use a Framework like AngularJs or knockoutJs. Commented Nov 24, 2014 at 10:31
  • Because your table isn't created in the DOM yet. Without a framework, you can only create DOM elements one by one. Commented Nov 24, 2014 at 10:34

3 Answers 3

2

Using Javascript :

document.querySelectorAll('#table-id tr:not(:first-child)')

Another solution using Javascript :

document.getElementById('table-id').children[1].children

Using JQuery :

$('#table-id tr:not(:first-child)')
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is, that you probably didn't insert your table into the HTML DOM. Otherwise it should work. You may also consider using the querySelector function instead of getElementsByTagName, so e.g. var rows = document.querySelector('tbody tr');

Comments

0

I use insertAdjacentHTML to parse string to HTML DOM

https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML

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.