Miguel Dutra
Miguel Dutra

Reputation: 86

JavaScript cloneNode: SELECT keeping some undesirable binding

So, I have a simple table containing input elements and I need to dynamically add new rows to it.

One of the cells contains a SELECT element and a list of OPTIONS which are replicated with cloneNode().

The problem is: when I change any of the replicated SELECT elements, the index of the original SELECT also changes to that same value, like if there was some sort of "binding" left behind by the cloning process.

My table looks something like this:

<table>
    <tr>
        <th>Header</th>
    </tr>
    <tr>
        <td>
            <select>
                <option>Options</option>
            </select>
        </td>
    </tr>
</table>

The cloning routine is relatively complex, as I have to change cell IDs, element names and other things, but it boils down to something like this:

var table = document.querySelector('#table');
var rows = table.querySelectorAll('tr');

for (var x = 0; x < 5; x++)
{

    row = rows[1].cloneNode(true);

    // Changes everything that needs to be changed

    table.appendChild(row);

}

Does anyone know what could be causing the original SELECT to be "bound" to the replicated ones?

Thanks in advance!

Upvotes: 0

Views: 140

Answers (1)

Miguel Dutra
Miguel Dutra

Reputation: 86

Thank you for all the comments! It turned out to be a simple mistake: I had an event added to the node via addEventListener() which was firing and updating the original SELECT to the same index of the replicated one.

Upvotes: 1

Related Questions