Reputation: 4246
I am trying to remove a td at runtime using Javascript only (no JQuery intended). Here is my table :
<table id = "tab">
<tr>
<td>
test 1
</td>
<td>
test 2
</td>
<td>
test 3
</td>
</tr>
</table>
Here is what I tryied :
function removeFirstTD() {
var element = document.getElementById("tab");
element.removeChild(element.firstChild);
}
Note that this function works and I execute it by doing this :
<body onload = "removeFirstTD();">
<!-- the tab is here -->
</body>
The problem is that it seems to erase the <tr>
because I didn't scope the tr before requesting remove the td. May someone help me doing this please ?
Upvotes: 0
Views: 4233
Reputation: 235
<table class="u-full-width">
<thead>
<tr>
<strong><td>Joke</td></strong>
</tr>
</thead>
<tbody>
<tr>
<td>This is a joke</td>
</tr>
</tbody>
</table>
I'm adding this to give a step by step procedure for beginners like me looking for this answer. Let's say above is how our table looks
First, get a DOM reference to the table body let tbody = document.querySelector('u-full-width').getElementsByTagName('tbody')
The above statements return a HTML Collection. So, we take the zero index of that collections tbody = tbody[0]
tbody.removeChild(tbody.firstElementChild)
firstElementChild
ignores text and comment nodes
Upvotes: 0
Reputation: 579
Use can also use querySelector. It picks the first element that matches it like this;
function removeFirstTD() {
var element = document.querySelector("#tab tr td");
element.remove();
}
Upvotes: 1
Reputation: 23396
Maybe the simplest way is to use HTMLTableElement Interface:
function removeFirstTD() {
var element = document.getElementById("tab");
element.rows[0].deleteCell(0);
}
Upvotes: 1
Reputation: 11238
You're close. td
elements belong to the tr
elements (and technically the tr
elements should belong to a tbody
element, not the table
directly). You need to get the tr
elements then find their first children.
function removeFirstTD() {
var element = document.getElementById("tab");
var tr = element.getElementsByTagName('tr');
var j = tr.length;
while (j--){
tr[j].removeChild(tr[j].firstChild);
}
}
Note that firstChild
might be whitespace or some other entity that is no the first td
element, and you should add a check for that before removing that child.
Upvotes: 0
Reputation: 66355
Due to white space (between the table
and tr
, and tr
and td
) this creates TEXTNODES which will be the first children, you would have to be more specific:
function removeFirstTD() {
var element = document.getElementById('tab');
var firstRow = element.getElementsByTagName('TR')[0];
var firstColumn = firstRow.getElementsByTagName('TD')[0];
firstColumn.remove();
}
But you might find this simpler and more reliable:
function removeFirstTD() {
document.querySelector('#tab tr td').remove();
}
Upvotes: 0
Reputation: 5964
Go down one more level?
element.firstChild.removeChild(element.firstChild);
Upvotes: 0