ボタンを押したら、テーブルの行を追加するJavascriptを作成しています。下記のような流れになっています。
- ボタンをクリック
- addButton() を実行
- 新要素
actionElm
、親要素、挿入場所直前の要素を取得 - insertBefore の処理
- エラー
ボタンをクリックするとエラーが発生します。
test_js.html:73 Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
新しいノードが挿入される前のノードは、このノードの子ではない。
Chromeの検証で追いかけてみると、親要素<table> actionTable
、親要素の中に子要素<tr> addButton
は確認できるので問題がなさそうに思えます。
エラーが発生するのは何が原因と考えられるでしょうか?
よろしくお願いします。
html
<table class="table" id="actionTable"> <tr> <th scope="col" style="width:5%">列1</th> <th scope="col" style="width:10%">列2</th> <th scope="col" style="width:60%">列3</th> <th scope="col" style="width:25%">列4</th> </tr> <tr> <td> <div> <input type="checkbox" name="data[2][delete]"> </div> </td> <td> <input type="hidden" name="data[2][id]" value="7"> <input type="text" name="data[2][name]" value="new4"> </td> <td><input type="text" name="data[2][url]" value="https://music.youtube.com"></td> <td><input type="text" name="data[2][memo]" value="memoemoemo"></td> </tr> <tr> <td> <div> <input type="checkbox" name="data[3][delete]"> </div> </td> <td> <input type="hidden" name="data[3][id]" value="8"> <input type="text" name="data[3][name]" value="new3"> </td> <td><input type="text" name="data[3][url]" value="https://youtube.com"></td> <td><input type="text" name="data[3][memo]" value="memoemoemo"></td> </tr> <tr id="addButton"> <td colspan="4"> <button type="button" onclick="addAction()">追加</button> </td> </tr> </table>
javascript
<script> function addAction() { let actionElm = document.getElementById('actionTemplate').content.cloneNode(true); let actionTable = document.getElementById('actionTable'); let addButton = document.getElementById('addButton'); actionTable.insertBefore(actionElm, addButton); } </script>
html
<template id="actionTemplate"> <tr> <td> <div class="custom-control custom-checkbox"> <input type="checkbox" name="data[-1][delete]"> </div> </td> <td> <input type="hidden" name="data[-1][id]" value="-1"> <input type="text" name="data[-1][name]" value=""> </td> <td><input type="text" name="data[-1][text]" value=""></td> <td><input type="text" name="data[-1][memo]" value=""></td> </tr> </template>
まだ回答がついていません
会員登録して回答してみよう