Reputation: 9621
I am using greasemonkey script and have updating the table using following code. I have attached the image of the table. But when I click on the delete , rowIndex returns -1 for all the rows. I am not getting why it is returning -1.
table = document.getElementById( 'keys-table' );
if ( !table ) return;
table.innerHTML = '';
// header
row = document.createElement( 'tr' );
th = document.createElement( 'th' );
th.innerHTML = "Group"; row.appendChild( th );
th = document.createElement( 'th' );
th.innerHTML = "Key"; row.appendChild( th );
th = document.createElement( 'th' );
th.innerHTML = " "; row.appendChild( th );
table.appendChild( row );
// keys
for ( i = 0 ; i < keys.length ; i++ ) {
row = document.createElement( 'tr' );
td = document.createElement( 'td' );
td.innerHTML = keys[i][0];
row.appendChild( td );
td = document.createElement( 'td' );
td.innerHTML = keys[i][1];
row.appendChild( td );
td = document.createElement( 'td' );
button = document.createElement( 'input' );
button.type = 'button';
button.value = 'Delete';
button.addEventListener( "click", function(event) {
DeleteKey( event.target.parentNode.parentNode.rowIndex,event.target);
}, false );
td.appendChild( button );
row.appendChild( td );
table.appendChild( row );
}
Upvotes: 1
Views: 902
Reputation: 187
Good question, and the answer of "am not I am" is correct, make sure to append a tbody to your table and then append your rows to this tbody.
Upvotes: 2
Reputation:
The tr
elements want to be in a <tbody>
element.
Usually the browser inserts one automatically, but if it did, you're wiping it out with...
table.innerHTML = '';
If you make sure that the original table has a <tbody>
, then do this...
table = document.getElementById( 'keys-table' );
if ( !table ) return;
var tbody = table.tBodies[0];
tbody.innerHTML = '';
...and then append the rows to tbody
, it will work.
Side note, but I'd personally recommend using DOM methods to remove the old rows instead of innerHTML
.
var tbody = table.tBodies[0];
while( tbody.firstChild )
tbody.removeChild( tbody.firstChild );
or
var tbody = table.tBodies[0];
while( tbody.rows[0] )
tbody.deleteRow( tbody.rows[0] );
Seems more proper.
Upvotes: 4