MHL
MHL

Reputation: 3

Regular expression for deleting a column using javascript?

So my HTML table looks like this:

<table class="mon_list" id="mon_list">
    <tr class='list'>
        <th class="list" align="center"><b>Klasse(n)</b></th>
        <th class="list" align="center">Stunde</th>
        <th class="list" align="center">Fach</th>
        <th class="list" align="center">Raum</th>
        <th class="list" align="center">Vertretungs-Text</th>
        <th class="list" align="center">Vertr-Text-2</th>
    </tr>
    <tr class='list odd'>
        <td class="list" align="center" style="background-color: #FFFFFF"><b>6.1</b></td>
        <td class="list" align="center" style="background-color: #FFFFFF">1 - 2</td>
        <td class="list" align="center" style="background-color: #FFFFFF">Ku</td>
        <td class="list" align="center" style="background-color: #FFFFFF">
            <s>312</s>006</td>
        <td class="list" align="center">&nbsp;</td>
        <td class="list" align="center">&nbsp;</td>
    </tr>
    ...
</table>

and I need to delete the last column. I cannot find a regular expression for that. I need to delete the 6th element in each row.

Upvotes: 0

Views: 84

Answers (2)

Felipe Valdes
Felipe Valdes

Reputation: 2217

This can be read as an XY problem, that is "how do I do X using Y", perhaps the question could be rephrased as, "how do I do X", I think in this case Y is the "regular expression".

I also think your code could use better formatting, would you mind editing the question?

in JavaScript you can remove rows by using the DOM removeChild() API passing the ID of the column row like so:

var rows = document.getElementById("tableObj").querySelector("tr");
for(var i=0;i<rows.length;i++){
    var cols = rows[i].querySelector("td");
    for(var r=0;r<cols.length;r++){
        if(r == 3){ //i.e. delete fourth column
            rows[i].removeChild(cols[r]);
        }
    }
}

Upvotes: 1

Michael Beeson
Michael Beeson

Reputation: 2875

If you want to remove a column, you could loop through each row and remove the cell at the specific position (in this case the last one)

var table = document.getElementById("myTable");
for (var i = 0, row; row = table.rows[i]; i++) {
    row.removeChild(row.cells[row.cells.length - 1]);
}

Let me know if that works

Upvotes: 1

Related Questions