Как удалить столбец из таблицы HTML с помощью JavaScript?

Опубликовано: 10 Декабря, 2021

Учитывая таблицу HTML, и задача состоит в том, чтобы удалить определенный столбец из таблицы HTML. Ниже рассматриваются два подхода:

Подход 1. Сначала выберите таблицу, а также получите строки таблицы с помощью table.rows . Получите количество столбцов в строке и просмотрите каждый столбец. Используйте str.search («someColumnName») (поскольку мы хотим удалить столбец с некоторым именем columnName), чтобы соответствовать текущему имени столбца и имени столбца, который мы хотим удалить. Если имя столбца совпадает, удалите каждую его ячейку с помощью метода .deleteCell (i) (где i - индекс столбца) путем обхода каждой строки таблицы.

Пример: этот пример реализует вышеупомянутый подход.

<!DOCTYPE HTML>
< html >
< head >
< title >
How to Remove Column from
HTML Table using JavaScript ?
</ title >
< style >
#myCol {
background: green;
}
table {
color: white;
margin: 0 auto;
}
td {
padding: 10px;
}
</ style >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< table id = "table" >
< colgroup >
< col id = "myCol" span = "2" >
< col style = "background-color:green" >
</ colgroup >
< tr >
< th >S.No</ th >
< th >Title</ th >
< th >Geek_id</ th >
</ tr >
< tr >
< td >Geek_1</ td >
< td >GeekForGeeks</ td >
< th >Geek_id_1</ th >
</ tr >
< tr >
< td >Geek_2</ td >
< td >GeeksForGeeks</ td >
< th >Geek_id_2</ th >
</ tr >
</ table >
< br >
< button onclick = "Geeks()" >
Click here
</ button >
< p id = "GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</ p >
< script >
function Geeks() {
var el_down = document.getElementById("GFG_DOWN");
var tble = document.getElementById('table');
var row = tble.rows; // Getting the rows
for (var i = 0; i < row [0].cells.length; i++) {
// Getting the text of columnName
var str = row [0].cells[i].innerHTML;
// If 'Geek_id' matches with the columnName
if (str.search("Geek_id") != -1) {
for (var j = 0 ; j < row.length; j++) {
// Deleting the ith cell of each row
row[j].deleteCell(i);
}
}
}
el_down.innerHTML =
"Column is removed from the table." ;
}
</script>
</ body >
</ html >

Выход:

Подход 2: выберите таблицу и получите строки таблицы, используя table.rows, чтобы пройти через всю таблицу. Получите индекс столбца в переменной (столбец, который мы хотим удалить). Удалите каждую ячейку методом .deleteCell (i) (где i - индекс столбца), пройдя по каждой строке таблицы.

Пример: этот пример реализует вышеупомянутый подход.

<!DOCTYPE HTML>
< html >
< head >
< title >
How to Remove Column from HTML
Table using JavaScript ?
</ title >
< style >
#myCol {
background: green;
}
table {
color: white;
margin: 0 auto;
}
td {
padding: 10px;
}
</ style >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< table id = "table" >
< colgroup >
< col id = "myCol" span = "2" >
< col style = "background-color:green" >
</ colgroup >
< tr >
< th >S.No</ th >
< th >Title</ th >
< th >Geek_id</ th >
</ tr >
< tr >
< td >Geek_1</ td >
< td >GeekForGeeks</ td >
< th >Geek_id_1</ th >
</ tr >
< tr >
< td >Geek_2</ td >
< td >GeeksForGeeks</ td >
< th >Geek_id_2</ th >
</ tr >
</ table >
< br >
< button onclick = "Geeks()" >
Click here
</ button >
< p id = "GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</ p >
< script >
function Geeks() {
var el_down = document.getElementById("GFG_DOWN");
// Getting the table
var tble = document.getElementById('table');
// Getting the rows in table.
var row = tble.rows;
// Removing the column at index(1).
var i = 1;
for (var j = 0; j < row.length ; j++) {
// Deleting the ith cell of each row.
row[j].deleteCell(i);
}
el_down.innerHTML =
"Column is removed from the table." ;
}
</script>
</ body >
</ html >

Выход: