Home > Blockchain >  How to swap HTMLTableCellElement nodes in a table
How to swap HTMLTableCellElement nodes in a table

Time:12-08

I have a HTML table like this:


<table id="myTable">
    <tbody>
        <tr>
            <td>
                <a href="/link_a.html">col A</a>
            </td>
            <td>
                <a href="/link_b.html"><span >col B</span></a>
            </td>
            <td>other cols
            </td>
        </tr>
        <tr>
            <td>value A
            </td>
            <td>value B
            </td>
            <td><span >more values</span>
            </td>
        </tr>
    </tbody>
</table>

In this table I want to copy via JavaScript some cells from one column to another (later I want to swap them, but to make it easier here I just want to overwrite some cells from others).

So I have written something like this:

    var tableObj = document.getElementById("mytable")
    for (var r of tableObj.rows) {
        var cell_store = {};
        for (var [i, c] of enumerate (r.cells)) {
            cell_store [i] = c;
        }
        r.cells [0] = cell_store [1];
    }

Basically I get the table object, iterate over the rows and over the columns getting HTMLTableCellElement nodes. I store some of these in a dictionary and then assign stored nodes to different cells in the table, but instead of a modified table I get an in-browser error "Uncaught (in promise) TypeError: 0 is read-only".

What do I do wrong here? How can I copy HTMLTableCellElement nodes (with all its sub-objects like links and spans) from one node to another?

CodePudding user response:

To manipulate DOM you should use DOM objects' methods. For you particular case use Node.appendChild. When you add a node to some other element it's removed from the previous one.

Also you can use element.innerHTML to swap rather HTML than nodes. In some cases working with pure HTML is faster than working with nodes. Benchmark your particular cases.

For your particular case just swap the cells with Node.insertBefore or something like that. Just learn DOM manipulation methods.

CodePudding user response:

I imagine you can accomplish what you want using. replaceWith So in your example r.cells [0].replaceWith(cell_store [1]);

You can also safely use remove, as long as you have a reference to the element you can always add it back using:

And more, have a look at MDN - Element docs for all methods.

  • Related